I want to make three ajax calls in a click event. Each ajax call does a distinct operation and returns back data that is needed for a final callback. The calls themselves are not dependent on one another, they can all go at the same time, however I would like to have a final callback when all three are complete.
$('#button').click(function() {
fun1();
fun2();
fun3();
//now do something else when the requests have done their 'success' callbacks.
});
var fun1= (function() {
$.ajax({/*code*/});
});
var fun2 = (function() {
$.ajax({/*code*/});
});
var fun3 = (function() {
$.ajax({/*code*/});
});
I asked the same question a while ago and got a couple of good answers here: Best way to add a 'callback' after a series of asynchronous XHR calls
Not seeing the need for any object malarky myself. Simple have a variable which is an integer. When you start a request, increment the number. When one completes, decrement it. When it's zero, there are no requests in progress, so you're done.
Here is a callback object I wrote where you can either set a single callback to fire once all complete or let each have their own callback and fire them all once all complete:
NOTICE
Since jQuery 1.5+ you can use the deferred method as described in another answer:
Example of deferred here
for jQuery < 1.5 the following will work or if you need to have your ajax calls fired at unknown times as shown here with two buttons: fired after both buttons are clicked
[usage]
for single callback once complete: Working Example
each having their own callback when all complete: Working Example
[The Code]
By default, all requests are sent asynchronously (i.e. this is set to true by default). If you need synchronous requests, set this option to
false
. Cross-domain requests anddataType: "jsonp"
requests do not support synchronous operation. Note that synchronous requests may temporarily lock the browser, disabling any actions while the request is active. As of jQuery 1.8, the use ofasync: false
with jqXHR ($.Deferred
) is deprecated; you must use the success/error/complete callback options instead of the corresponding methods of the jqXHR object such asjqXHR.done()
or the deprecatedjqXHR.success()
.I'm sorry but I can't explain what I worte cuz I'm a Korean who can't speak even a word in english. but I think you can easily understand it.
It's worth noting that since
$.when
expects all of the ajax requests as sequential arguments (not an array) you'll commonly see$.when
used with.apply()
like so:This is because
$.when
accepts args like thisAnd not like this: