views:

258

answers:

3

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)

+1  A: 

You may take a look at the queue plugin.

Darin Dimitrov
yes, had a quick look, though that seems a bit overkill
second
+1  A: 
var msg= $("<div style='height:100px;width:200px; background:#000;color:#fff; line-height:100px;text-align:center;position:fixed;top:50%;left:50%;z-index:1000;margin-left:-100px; margin-top:-50px'>Ajax done! Click Me!</div>")
.click(function(){
$(msg).fadeOut(1000,function(){
   $(this).remove();
   });
})

$(document).ajaxStop(function(){
  $('body').append(msg);
})

the point is attaching ajaxStop() event to document for global check. you might be more specific if you want.

ilhan negis
+2  A: 

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();
});
Nick Craver