I found this little example on jquery documentation page. I always tried returning value from ajax function and I was always told that there is some problem of sync and async thing and I can’t return value out of $.ajax function without making it async.
$.ajax({
url: "test.html",
context: document.body
}).done(function() {
$(this).addClass("done");
});
In the example above, on what this done function is applied(whats being used as $(this) in example).
one more thing, as the ajax function can’t set global variables, can’t the be set in this done too? cant I return value out of done function either?
$.ajaxreturns a jqXHR object (see first section after the configuration parameter description) wich implements the promise interface and allows you to add callbacks and get notified of changes of the Ajax call.Inside the callbacks for
$.ajax,thisrefers to the objectcontextrefers to in the configuration or the jqXHR instance ifcontextwas not set. In this case it refers todocument.body:This and more is all explained in the documentation: http://api.jquery.com/jQuery.ajax/
That is not correct, any function can set global variables. The problem with asynchronous functions is that you are likely accessing the variable before it was set.
See above
You can return a value (as in putting a
returnstatement inside the callback), but you cannot return it to your code, since jQuery is calling the callback internally and just ignoring the return value.