formdata in ajax call - asp.net

When I pass formdata in ajax call after json return it does not return on Success or error block just printing value on browser
// And my Controller side code is
[HttpPost]
public JsonResult Create(InquiryModel model)
{
var inquiry = _inquiryService.GetInquiryById(model.Id);
return Json(inquiry.Id, JsonRequestBehavior.AllowGet);
}
// View side
var formData = new FormData();
jQuery.each(jQuery('#QuotationDocument')[0].files, function (i, file) {
formData.append('file-' + i, file);
});
$.ajax({
url: '#Url.Action("Create", "Inquiry")',
data: formData,
contentType: false,
processData: false,
type: "POST",
success: function (data) {
alert("ssss");
},
error: function (msg) {
alert("error", msg.statusText + ". Press F12 for details");
}
});
when I pass only formData it works fine

Try like this;
$.ajax({
url: '#Url.Action("Create", "Inquiry")',
data: formData,
datatype: "json",
type: "POST",
success: function (data) {
alert("ssss");
},
error: function (msg) {
alert("error", msg.statusText + ". Press F12 for details");
}
});

Related

put the word "Please Wait, Don't Close The Windows" on Ajax Loading

I am using partial view for my projects.
My Ajax Code is Here :
$("#btnAdd").on("click", function () {
var formData = new FormData();
var dhnFiles = $("#fileDHN")[0].files;
if (dhnFiles.length == 0) {
alert("Pilih file DHN terlebih dahulu!");
return;
}
for (var i = 0; i < dhnFiles.length; i++) {
formData.append("DataDHN", dhnFiles[i]);
}
$.ajax({
method: "POST",
url: "#Url.Action("PartialViewTableDataDHN")",
data: formData,
contentType: false,
processData: false
}).done(function (data) {
$("#TableDHN").html(data);
}).fail(function () {
alert("Error submitting data to server.");
});
});
The loading about 20minutes. and I want the user wait and don't close the windows.
How do i add the words 'Please wait, don't close the windows' while loading.
Thank you.
you can perhaps add a overlay div which you can show using the beforeSend pre-request callbak... then you can hide the ovelay message when ajax is completed...
$.ajax({
method: "POST",
url: "#Url.Action("PartialViewTableDataDHN")",
data: formData,
contentType: false,
processData: false,
beforeSend: function( xhr ) {
$('#overlay_message').show();
}
}).done(function (data) {
$("#TableDHN").html(data);
}).fail(function () {
alert("Error submitting data to server.");
}).completed(function(){
$('#overlay_message').hide();
});
See how to create an overlay: https://www.w3schools.com/howto/howto_css_overlay.asp

angularjs repeat does not show data at first time

First, I am so sorry because of my English.
I am showing a table that it's data come from server and shown with angular repeat.
I make a ng-click on each row of table that send an ajax request and get another list that I want to show in another table, until now all the thing are right,
but I have a little problem, my problem is that I must click twice on my first table's row to show second table data, at first time all the data comes from server but did not show in second table, my angular code is shown below.
angular.module("BI", [])
.controller("ListTables", function ($scope, $http) {
$scope.ReportLst = [];
$scope.myData = {};
$scope.myData.ReportLst = [];
$scope.myData.ReportDetail = [];
$scope.myData.ReportDetail2 = [];
$scope.selectedReportval = "";
$scope.Load = function () {
$http.post('MakeReport.aspx/LoadReportLst', { data: {} })
.success(function (data) {
$scope.myData.ReportLst = JSON.parse(data.d);
})
.error(function (data, status) {
alert('error');
});
}
$scope.SelectRepID = function (val) {
$.ajax({
type: "POST",
url: "MakeReport.aspx/GetReportDetail",
contentType: "application/json; charset=utf-8",
data: "{ 'val': '" + val + "'}",
dataType: "json",
success: function (data) {
$scope.myData.ReportDetail = JSON.parse(data.d);
},
error: function (data, status, jqXHR) {
alert(data.d);
}
});
$scope.selectedReportval = val;
}
});
In your second request you're using $.ajax instead of $http, because this isn't an Angular function a digest won't be triggered and your view won't be updated, in order to fix this you have to use $http there too.
$scope.SelectRepID = function (val) {
$http.post({
url: "MakeReport.aspx/GetReportDetail",
contentType: "application/json; charset=utf-8",
data: "{ 'val': '" + val + "'}",
dataType: "json"
}).then(
function(data) {
$scope.myData.ReportDetail = JSON.parse(data.d);
}, function(error) {
alert(error);
}
);
$scope.selectedReportval = val;
}
Update: Another way would be to use a $timeout in your $.ajax success function like so (this will trigger a digest).
success: function (data) {
$timeout(function() {
$scope.myData.ReportDetail = JSON.parse(data.d);
});
}

how to call popup window while ajax callback post method waiting to response in asp.net

1) my call back function
function fetch_servicedata1() {
var filename = document.getElementById("ctl00_ContentMain_hdnfile").value;
companyID = document.getElementById('ctl00_ContentMain_hdnCompanyID').value;
var service_Res = "";
$.ajax({
type: "POST",
url: "UtilityService.asmx/New_FatchCacheXMLString",
data: "filename=" + filename + "&CompanyID=" + companyID+"&Rq_CID=1",
dataType: "xml",
// cache: false,
async: false,
success: function (xml) {
// alert('first relsut');
if (xml.documentElement.text) {
fnFetchResult_New(xml.documentElement.text);
}
else {
fnFetchResult_New(xml.documentElement.textContent);
}
if(TotalResultCount>0)
document.getElementById("divProgressBar").style.display = '';
secondPagingFlag = true;
console.log('before func 2');
// setTimeout(fetch_servicedata2(), 1);
},
error: function (xhr, ajaxOptions, thrownError) {
// alert(xhr.status);
// alert(thrownError);
// $('#waitScreen').css('display', 'none'); $('#waitBox').css('display', 'none');
}
});
}
2) my event
$(".external-link").live("click", function (e) {
$.ajax({
type: "GET",
async: true,
url: "",
success: function () {
window.open("HtlIntermediate.aspx");
}
})
});
i need to event call without wait for call back success
i have called call back function and it will take around 1 minute to response and in the meantime need to click on the button and open popup window which show data from database using asp.net
you can use beforeSend and complete parameter in jquery ajax
http://api.jquery.com/jquery.ajax/
$.ajax({
type: "GET",
async: true,
beforeSend:function(){window.open("HtlIntermediate.aspx"); },
complete:function(){//close window
},
url: "",
success: function () {
// process other stuff
}
})

Unknown web method in asp.net

In the below code I have a textbox .My aim is when I focus on textbox it will call the server side code through ajax.But I got a error unknown web method txtField_GotFocus parameter name method name.Please help me to rectify the error.
design code:
$(document).ready(function () {
$("#<%=txtField.ClientID%>").bind("focus", function () {
$.ajax({
type: "POST",
url: "<%=Request.FilePath%>/txtField_GotFocus",
data: "{}",
contentType: "application/json",
dataType: "json",
success: function (msg) {
//alert("success message here if you want to debug");
},
error: function (xhr) {
var rawHTML = xhr.responseText;
var strBegin = "<" + "title>";
var strEnd = "</" + "title>";
var index1 = rawHTML.indexOf(strBegin);
var index2 = rawHTML.indexOf(strEnd);
if (index2 > index1) {
var msg = rawHTML.substr(index1 + strBegin.length, index2 - (index1 + strEnd.length - 1));
alert("error: " + msg);
} else {
alert("General error, check connection");
}
}
});
});
});
<asp:TextBox ID="txtField" runat="server" AutoPostBack="true" OnTextChanged="txtField_TextChanged" ClientIDMode="Static"></asp:TextBox>
field.ascx:
public static void txtField_GotFocus()
{
string foo = HttpContext.Current.Request["foo"];
//code...
}
You are missing [WebMethod] annotation. Also i have modified your code
[WebMethod]
public static string txtField_GotFocus()
{
string foo = HttpContext.Current.Request["foo"];//oops i got my super data
//code...
return "awesome, it works!";
}
Check this Article
Your refactored ajax code
$(document).ready(function () {
$("#<%=txtField.ClientID%>").bind("focus", function () {
$.ajax({
type: "POST",
url: "<%=Request.FilePath%>/txtField_GotFocus",
data: "{foo:'whatever'}",
success: function (msg) {
alert(msg);//awesome, it works!
},
error: function (xhr) {
}
});
});
});
Data returned form Server is stored in msg.d field. If you return a single value, you should get it using msg.d. If you return a JSON serialized object you have to parse it using JSON.parse(msg.d)
$(document).ready(function () {
$("#<%=txtField.ClientID%>").bind("focus", function () {
$.ajax({
type: "POST",
url: "<%=Request.FilePath%>/txtField_GotFocus",
data: "{foo:'whatever'}",
success: function (msg) {
alert(msg.d);//awesome, it works!
},
error: function (xhr) {
}
});
});
});

Passing parameters in ajax call

I'm trying to make an ajax call to the controller method. without parameter it works fine. Once i add the parameter i always receive a null parameter to the cotroller. I think i have correctly done the parameter passing in ajax call.
<script type="text/javascript">
$(document).ready(function () {
$('#lstStock').change(function () {
var serviceURL = '<%= Url.Action("GetStockPrice", "Delivery") %>';
var dropDownID = $('select[id="lstStock"] option:selected').val();
alert(dropDownID); // here i get the correct selected ID
$.ajax({
type: "POST",
url: serviceURL,
data: '{"stockID":"' + dropDownID + '"}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: successFunc,
error: errorFunc
});
function successFunc(data, status) {
alert(data.Result);
}
function errorFunc() {
alert('error');
}
})
});
</script>
Controller:
[HttpGet]
public ActionResult GetStockPrice()
{
return View();
}
[HttpPost]
[ActionName("GetStockPrice")]
public ActionResult GetStockPrice1(string stockID)//I get the null parameter here
{
DeliveryRepository rep = new DeliveryRepository();
var value = rep.GetStockPrice(stockID);
return Json(new { Result = value }, JsonRequestBehavior.AllowGet);
}
It's because you are treating the data as a string
data: '{"stockID":"' + dropDownID + '"}',
you can change it to:
data: { stockID: dropDownID },
in some cases, depending on the parameter declared in your controller method, you need to serialize the data. If you need to do that then this is how you would do it:
var o = { argName: some_value };
$.ajax({
// some other config goes here
data: JSON.stringify(o),
});
try data: { stockID : dropDownID},
$('#lstStock').change(function () {
var serviceURL = '<%= Url.Action("GetStockPrice", "Delivery") %>';
var dropDownID = $('select[id="lstStock"] option:selected').val();
// $(this).val(); is better
alert(dropDownID); // here i get the correct selected ID
$.ajax({
type: "POST",
url: serviceURL,
data: { stockID : dropDownID},
....
Try specifying:
data: { stockID : dropDownID },
It looks like you're passing up "stockID" not stockID.
A good tool to use for this is Fiddler, it will allow you to see if the Controller action is hit and what data was sent upto the server.

Resources