views:

84

answers:

1

I have a jQuery application that loads data from five asynchronous server calls. I do not want to display any data until all five calls return. (I plan on displaying a Loading message until that happens.)

How can I detect when all five calls have returned? I considered having each callback method increment a variable (using jQuery's data() method, perhaps) and then waiting for the value to become 5. (I am not sure yet how I would listen for that event.) I do not think this is a very good solution, however. What would happen if two calls return at the same time?

Is there a better way to do this?

+6  A: 

If you are already using jQuery for the AJAX calls, you can use $.ajaxStop() for this, it fires when all current calls come back, you can use it like this:

$("#loading").ajaxStop(function() {
  $(this).fadeOut();
});

This isn't really that different than .click() in terms that it's just an event, you can use the ajaxStop event yourself if you want, like this:

$("#loading").bind('ajaxStop', function() {
  $(this).fadeOut();
});
Nick Craver
Couldn't explain it better! :)
Danny Herran
+1 - Once again you've shown me something I never knew jQuery did. I've been using a counter variable this whole time ..
Matt
This works beautifully. Thank you!
Jeremy