Last Updated: February 25, 2016
·
10.69K
· guido

Execute code after a set of AJAX calls using jQuery

The other day I had some code I needed to execute after a set of AJAX calls. Of course I wanted to keep my calls asynchronous, and execute them all at once, as I don't like slow websites.

The solution to this problem is rather simple. jQuery built an event called ajaxStop for this sole purpose. This event gets fired each time an ajax call finishes and no other ajax calls are running on the current page.

So, without further ado, the code for your copy/paste pleasure:

jQuery(function($)
{
  $(document).ajaxStop(function()
  {
    // Executed when all ajax requests are done.
  });
});

If you're working with multiple sets of AJAX requests it might come in handy to set a variable before starting the AJAX requests, and checking if it's set to make sure you're not executing your actions after the wrong set of AJAX requests.