jquery multiple ajax check for all done? (order not important)

ajax, jquery

Solution

The `.ajaxStop()` method is available for this, it only fires when the last of the current ajax requests finishes. Here's the full description:

Whenever an Ajax request completes, jQuery checks whether there are any other outstanding Ajax requests. If none remain, jQuery triggers the `ajaxStop` event. Any and all handlers that have been registered with the `.ajaxStop()` method are executed at this time.

For example if you wanted to just run something, document is a good place to hook in:

$(document).ajaxStop(function() {
  //all requests finished!, do something with all your new fancy data
});

Or you could display a message when this happens, like this:

$("#ajaxProgressDiv").ajaxStop(function() {
  //display for 2 seconds then fade out
  $(this).text("All done!").delay(2000).fadeOut();
});

Problem

Is there a neat way to make sure a bunch of ajax callbacks have all finished? They don't need to be executed in order, i just need all the data to be there. one idea is to have them all increment a counter on completion and check if counter == countMax, but that seems ugly. Also, are there sync issues? (from simultaneous read/write to the counter)

Original source