Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

jquery

ajax

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)

like image 825
second Avatar asked Dec 30 '22 04:12

second


2 Answers

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();
});
like image 151
Nick Craver Avatar answered Jan 03 '23 18:01

Nick Craver


You may take a look at the queue plugin.

like image 41
Darin Dimitrov Avatar answered Jan 03 '23 16:01

Darin Dimitrov