Jeremy
Jeremy

Reputation: 9467

jQuery: How to fire event when all asynchronous calls return?

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?

Upvotes: 1

Views: 853

Answers (1)

Nick Craver
Nick Craver

Reputation: 630409

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

Upvotes: 8

Related Questions