I find a fantastic bug when I use jQuery ajax to do a request to web service:
var AjaxResult;
login = function () {
AjaxResult = "";
$.ajax({
type: "POST",
url: KnutBase.getServiceUrl() + "ServiceInterface/HmsPlannerWebService.asmx/AuthenticateLogin",
data: { username: this.username, password: this.password },
dataType: 'jsonp',
success: function (response) {
//the response value is 'success'
AjaxResult = response;
},
error: function (data, status, e) {
alert("error:" + e);
}
});
//alert(AjaxResult);
//if i do not alert a message here, this function will return a null value
//however, i do alert here, then i get a 'success' value.
return AjaxResult;
}
How could this happen. I am confused as to why the AjaxResult returns its value before the ajax method set response value to it.
You can't. It's just impossible. If your code really tries to do that, it will fail.
Since ajax is asynchronous,
return AjaxResult
is actually executed before the ajax result completes. You can not return in this way; you need to perform some action in the callback of the ajax requests or use deferred.Ajax is
asynchronous
call to your method and it do the processing in the back for server trip. You will not get the result until thesuccess
method is called. You can read more about jquery ajax hereYou can set
async
attribute tofalse
ofajax()
to make a synchronous call.EDIT: Using deferreds --
$.Deferred
can be used to run code after some other code has completed. Ajax is an excellent example, and all of the jQuery ajax methods (except.load
) implement the$.Deferred
interface. You can use$.when
to watch deferreds. For example:The deferred gets returned from the method above, so you can do the following:
Any code that needs to be synchronized with the ajax response has to go in the
.done
callback.Note that this is not much different than just using the
success
callback with$.ajax
. The point is that all of your work that relies on what is returned from Ajax needs to be done in these callbacks.It has to do with the fact that AJAX is asynchronous (that's actually the meaning of the first A in it).
alert
stops the code until you press the button, and the request has time to complete. With noalert
, the function proceeds immediately, the AJAX has barely begun its work, and of course the value is still empty.Generally, you can't have functions return values that they get from AJAX. Set up a callback for it, and deal with it when it comes.