Jquery Ajax Call, doesn't call Success or Error [duplicate] - javascript

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How do I return the response from an asynchronous call?
I am using Jquery Ajax to call a service to update a value.
function ChangePurpose(Vid, PurId) {
var Success = false;
$.ajax({
type: "POST",
url: "CHService.asmx/SavePurpose",
dataType: "text",
data: JSON.stringify({ Vid: Vid, PurpId: PurId }),
contentType: "application/json; charset=utf-8",
success: function (data) {
Success = true;//doesn't go here
},
error: function (textStatus, errorThrown) {
Success = false;//doesn't go here
}
});
//done after here
return Success;
}
and Service:
[WebMethod]
public string SavePurpose(int Vid, int PurpId)
{
try
{
CHData.UpdatePurpose(Vid, PurpId);
//List<IDName> abc = new List<IDName>();
//abc.Add(new IDName { Name=1, value="Success" });
return "Success";
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
the service is being called Successfully from the AJAX. Value is also being Changed. But after the Service, success: or error: functions are not being called, in this case success should have been called but it is not working.
I used firebug and found that, the success or error functions are being skipped and goes directly to return Success;
Can't seem to find what's the problem with the code.
Update:
adding async: false fixed the problem

change your code to:
function ChangePurpose(Vid, PurId) {
var Success = false;
$.ajax({
type: "POST",
url: "CHService.asmx/SavePurpose",
dataType: "text",
async: false,
data: JSON.stringify({ Vid: Vid, PurpId: PurId }),
contentType: "application/json; charset=utf-8",
success: function (data) {
Success = true;
},
error: function (textStatus, errorThrown) {
Success = false;
}
});
//done after here
return Success;
}
You can only return the values from a synchronous function. Otherwise you will have to make a callback.
So I just added async:false, to your ajax call
Update:
jquery ajax calls are asynchronous by default. So success & error functions will be called when the ajax load is complete. But your return statement will be executed just after the ajax call is started.
A better approach will be:
// callbackfn is the pointer to any function that needs to be called
function ChangePurpose(Vid, PurId, callbackfn) {
var Success = false;
$.ajax({
type: "POST",
url: "CHService.asmx/SavePurpose",
dataType: "text",
data: JSON.stringify({ Vid: Vid, PurpId: PurId }),
contentType: "application/json; charset=utf-8",
success: function (data) {
callbackfn(data)
},
error: function (textStatus, errorThrown) {
callbackfn("Error getting the data")
}
});
}
function Callback(data)
{
alert(data);
}
and call the ajax as:
// Callback is the callback-function that needs to be called when asynchronous call is complete
ChangePurpose(Vid, PurId, Callback);

Try to encapsulate the ajax call into a function and set the async option to false. Note that this option is deprecated since jQuery 1.8.
function foo() {
var myajax = $.ajax({
type: "POST",
url: "CHService.asmx/SavePurpose",
dataType: "text",
data: JSON.stringify({ Vid: Vid, PurpId: PurId }),
contentType: "application/json; charset=utf-8",
async: false, //add this
});
return myajax.responseText;
}
You can do this also:
$.ajax({
type: "POST",
url: "CHService.asmx/SavePurpose",
dataType: "text",
data: JSON.stringify({ Vid: Vid, PurpId: PurId }),
contentType: "application/json; charset=utf-8",
async: false, //add this
}).done(function ( data ) {
Success = true;
}).fail(function ( data ) {
Success = false;
});
You can read more about the jqXHR jQuery Object

Related

how to create a javascript rusable class to pass parameters to ajax

im new in JS,im looking for a way to create a class or function,reusable everywhere in my code,just pass it parameters and get the result,because currently I am doing like this:
$.ajax({
dataType: "json",
type: "POST",
url: "#Url.Action("power","Ranking")",
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ "regionalManager": tmpString }),
success: function (result) {
})}
I write this every time I need, and im sick of it,
function sendAjaxCustom(DataType,Type,Url,Ctype,Data){
$.ajax({
dataType: DataType,
type: Type,
url: Url,
contentType: Ctype,
data: Data,
success: function (result) {
return result;
})}
}
You can call this function in JS like
var result = sendAjaxCustom("json","POST",'#Url.Action("power","Ranking")',"application/json; charset=utf-8",JSON.stringify({ "regionalManager": tmpString }));
you will have the result in result variable.
You can create a function like this
function ajax(url, data) {
$.ajax({
dataType: "json",
type: "POST",
url: url,
contentType: "application/json; charset=utf-8",
data: data,
success: function (result) {
})}
}
Pass the url if it's dynamic and the object data on the second parameter.
Just create a simple function with your variables that need to change between calls and return the $.ajax result from there.
function ajaxWrapper(url, data, callback) {
return $.ajax({
dataType: 'json',
type: 'POST',
url: url,
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(data),
success: callback
});
}
When you want to call it:
ajaxWrapper('http://www.google.com/', { hello: 'world' }, function(result) {
console.log(result);
});
With the callback it's much more reusable, since you can use this anywhere and change what you do on completion of the function wherever you use it.
A simple solution is to return an object and pass it to the ajax and if some change is required then you can update the properties of the object before calling the ajax service
function commonAjaxParams() {
return {
dataType: "json",
type: "POST",
url: "#Url.Action("power","Ranking")",
contentType: "application/json; charset=utf-8",
//and so on that are common properties
}
}
//now in your application first call the function to get the common props
var commonParams = commonAjaxParams();
//change or add an parameter to your liking
commonParams.type = 'GET';
commonParams.success = function(){...} //if this action is need
commonPramss.error = function(){...}
//now call you ajax action
$.ajax(commonParams)
There is another way in which you may call the ajax function and you may get success, fail response return.
The benefit is you manage success or fail response independently for each ajax request.
$(document).ready(function() {
function ajaxRequest(dataType, requestMethod, dataURL, jsonData) {
return $.ajax({
dataType: dataType,
type: requestMethod,
url: dataURL,
contentType: "application/json; charset=utf-8",
data: JSON.stringify(jsonData)
});
}
var jsonData = {
"regionalManager": "jason bourne"
};
ajaxRequest(
"json",
"POST"
"#Url.Action('power','Ranking')",
jsonData)
.success((data) {
console.log("success");
}).error((err) {
console.log("error");
}).done(() {
console.log("done");
});
});

Ajax jquery to stop running when windows is closed

All,
I am new to MVC. I have built an application where a button click performs
get market data (lengthy operation).
data message and upload to database.
This is what the JavaScript function looks like:
function OnClick(s, e) {
if (true) {
$.ajax({
type: "POST",
url: "#Url.Action("DataFileUpload", "ImportData")",
data: JSON.stringify({ positionDate: positionDate }),
dataType: "text",
contentType: "application/json; charset=utf-8",
beforeSend: function () { lpImport.Show(); },
success: function (msg) {
ImportDataGridView.PerformCallback();
ImportSuccessMessage.SetVisible(true);
ImportSuccessMessage.SetText(msg);
lpImport.Hide();
},
error: function (xhr) {
alert(xhr)
ImportDataGridView.PerformCallback();
}
});
}
}
What is happening right now is - When users close the browser in the middle of the run, controller action is still running. I can see that in my log.
How do I make browser close to stop running my controller action DataFileUpload ?
Thanks for helping out.
you can use the abort function from the XMLHttpRequest that $.ajax() returns.
abort(). If the request has been sent already, this method will abort the request.
Something like:
var xhr;
function OnClick(s, e) {
if (true) {
xhr = $.ajax({
type: "POST",
url: "#Url.Action("DataFileUpload", "ImportData")",
data: JSON.stringify({ positionDate: positionDate }),
dataType: "text",
contentType: "application/json; charset=utf-8",
beforeSend: function () { lpImport.Show(); },
success: function (msg) {
ImportDataGridView.PerformCallback();
ImportSuccessMessage.SetVisible(true);
ImportSuccessMessage.SetText(msg);
lpImport.Hide();
},
error: function (xhr) {
alert(xhr)
ImportDataGridView.PerformCallback();
}
});
}
}
function closeBrowser() {
xhr.abort();
}
but this will only cancel the event on the client. You should also cancel the request on the serverside.

Start ajax request when other ajax request is running

In C# .NET it seems not to be possible to run 2 ajax request simultaneous. This is my Javascript code:
function startAjaxRequest1() {
setTimeout(startAjaxRequest2, 2000);
$.ajax({
type: "POST",
url: "/test.ashx/status",
contentType: "text/html; charset=utf-8",
dataType: "html",
async: true,
success: function (response) {},
failure: function (response) {}
});
}
function startAjaxRequest2() {
$.ajax({
type: "POST",
url: "/test2.ashx/statusupdate",
contentType: "text/html; charset=utf-8",
dataType: "html",
success: function (response) {},
failure: function (response) {}
});
}
When Ajax request 1 is executing, request 2 (started after 2 seconds), will never start. When I remove request 1, request 2 is executed is performing well.
Is it not possible to start a second ajax request when another is buzzy?
UPDATE:
In fact, this is my first ajax request (send files to server). Maybe it has something to do with this. The second ajax request keeps requesting each 4 seconds untill $.ajax(options) hass succeeded and the inner Ajax request is started. From that time, second request stops requesting. If I remove the inner Ajax request, there is no problem.
var options = {};
options.url = "/uploadGeoJsonFiles.ashx";
options.type = "POST";
options.data = data;
options.contentType = false;
options.processData = false;
options.success = function (result) {
$.ajax({
type: "POST",
url: "/dashboard.aspx/importGeoJsonData",
data: jsonString,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
},
failure: function (response) {
}
});
};
options.error = function (err) {
showError(err.statusText);
};
$.ajax(options);

Call function after ajax load()

I initiate a function after an ajax load(), but the function I intimate calls upon an additional function, which isn't working. How do I initiate ajaxstuff() after load()?
function ajaxstuff(data) {
$.ajax({
type: "POST",
url: "do-it.php",
data: {data},
success: function() {
console.log('I got this far'); // this doesn't work / isn't called
}
});
}
function doit() {
$('form').submit(function(e) {
e.preventDefault();
var formData = new FormData(this);
console.log('I got this far'); // this works
ajaxstuff(formData);
}
}
$('.popup-loader').click(function() {
$(this).append('<div class="popup"></div>');
$('.popup').load('popup.php', function() {
doit(); // this works
}
});
Check for errors in your console, also, in your AJAX add an async option. set it to FALSE ("Setting async to false means that the statement you are calling has to complete before the next statement in your function can be called"):
function ajaxstuff(data) {
$.ajax({
async: false,
type: "POST",
url: "do-it.php",
data: data,
success: function(result) {
console.log(result); //check in your console for errors
}
});
}
Syntax error in ajaxstuff function. data: {data}, , probably should be data: data,
Also when you're passing a FormData object to $.ajax, you have to specify processData: false and contentType: false
$.ajax({
type: "POST",
url: "do-it.php",
data: data,
processData: false,
contentType: false,
success: function() {
console.log('I got this far');
}
});

"undefined" for alerting an ajax call response , why?

i am trying to alert the return value captured by the ajax request. The web method it is refering is returning a boolean value of true or false, and when i am trying to access it outside the ajax method it gives a message "undefined" :?
<script type="text/javascript" language="javascript">
$(document).ready(function () {
var authInfo;
$.ajax({
type: "POST",
url: "service.asmx/getAuthInfo",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
authInfo = msg.d;
},
});
alert(authInfo);
});
</script>
why is the alert(authInfo) giving me as "undefined" ?? Please help !
where does this piece of code fit on the above context ?
if(auhthInfo){
$(".ansitem").editable('FetchUpdate.aspx', {
style: 'background-color:inherit;',
type: 'textarea',
indicator: '<img src="spinner.gif">',
event: 'dblclick',
onblur: 'submit',
submitdata: function (value, settings) {
return { orgval: value};
},
});
};
Your "$.ajax()" call is asynchronous, and thus the results are not available until the response is returned from the server.
If you put your "alert()" inside the "success" callback, it should work (if the HTTP transaction works).
EDITED TO HANDLE YOUR NEW CODE:
<script type="text/javascript" language="javascript">
$(document).ready(function () {
var authInfo;
$.ajax({
type: "POST",
url: "service.asmx/getAuthInfo",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
// alert(msg.d); // here it will work as it is only called when it succeeds.
MyHanlder(msg);
},
});
// alert(authInfo); // here authinfo has no value as the AJAX call may not have returned.
});
function MyHandler(msg) {
if(msg.d){
$(".ansitem").editable('FetchUpdate.aspx', {
style: 'background-color:inherit;',
type: 'textarea',
indicator: '<img src="spinner.gif">',
event: 'dblclick',
onblur: 'submit',
submitdata: function (value, settings) { return { orgval: value}; },
});
};
}
</script>
The request and the response that you get via ajax calls are asynchronous. I think it is not possible to alert the value that you get in response at the end of ready function because you are not assured that you will be getting your response before the function completes execution.
You are alerting the authInfo variable before the actual ajax call have returned. If you try this:
success:function(msg) {
authInfo = msg.d;
alert(authInfo);
}
I think you will get the correct result.
Because the AJAX call is done asynchronously, the alert does not have the value at the time of execution. If you place the alert inside the success function you should see the appropriate results. I also noticed you have an extra comma in the $.ajax parameters after the success function parameter.
It appears:
alert(authInfo);
Is running immediately when your document is ready.
However, the variable is not being initialized until after the AJAX call completes.
Try moving the alert to:
$.ajax({
type: "POST",
url: "service.asmx/getAuthInfo",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
authInfo = msg.d;
alert(authInfo);
},
});
If you need to do anything more complex with the value, you can try re-factoring the code into another function:
function onSuccess(msg)
{
if(msg.d)
{
window.alert('The value is true!');
}
else
{
window.alert('The value is false!')
}
}
$.ajax({
type: "POST",
url: "service.asmx/getAuthInfo",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: onSuccess,
});

Categories