Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wait until all jQuery Ajax requests are done?

How do I make a function wait until all jQuery Ajax requests are done inside another function?

In short, I need to wait for all Ajax requests to be done before I execute the next. But how?

like image 406
jamietelin Avatar asked Sep 14 '10 14:09

jamietelin


People also ask

How do I make jQuery wait for an Ajax call to finish before it returns?

ajax({ url: $(this). attr('href'), type: 'GET', async: false, cache: false, timeout: 30000, fail: function(){ return true; }, done: function(msg){ if (parseFloat(msg)){ return false; } else { return true; } } }); });

How do you check if all AJAX calls are completed?

The ajaxStop() method specifies a function to run when ALL AJAX requests have completed.

Can we execute run multiple Ajax request simultaneously in jQuery?

How to Run Multiple AJAX Requests in jQuery. jQuery . when() provides a way to execute callback functions based on zero or more Thenable objects , usually Deferred objects that represent asynchronous events .


2 Answers

If you want to know when all ajax requests are finished in your document, no matter how many of them exists, just use $.ajaxStop event this way:

$(document).ajaxStop(function () {   // 0 === $.active }); 

In this case, neither you need to guess how many requests are happening in the application, that might finish in the future, nor dig into functions complex logic or find which functions are doing HTTP(S) requests.

$.ajaxStop here can also be bound to any HTML node that you think might be modified by requst.


Update:
If you want to stick with ES syntax, then you can use Promise.all for known ajax methods:

Promise.all([ajax1(), ajax2()]).then(() => {   // all requests finished successfully }).catch(() => {   // all requests finished but one or more failed }) 

An interesting point here is that it works both with Promises and $.ajax requests.

Here is the jsFiddle demonstration.


Update 2:
Yet more recent version using async/await syntax:

try {   const results = await Promise.all([ajax1(), ajax2()])   // do other actions } catch(ex) { } 
like image 29
Arsen Khachaturyan Avatar answered Oct 02 '22 05:10

Arsen Khachaturyan


jQuery now defines a when function for this purpose.

It accepts any number of Deferred objects as arguments, and executes a function when all of them resolve.

That means, if you want to initiate (for example) four ajax requests, then perform an action when they are done, you could do something like this:

$.when(ajax1(), ajax2(), ajax3(), ajax4()).done(function(a1, a2, a3, a4){     // the code here will be executed when all four ajax requests resolve.     // a1, a2, a3 and a4 are lists of length 3 containing the response text,     // status, and jqXHR object for each of the four ajax calls respectively. });  function ajax1() {     // NOTE:  This function must return the value      //        from calling the $.ajax() method.     return $.ajax({         url: "someUrl",         dataType: "json",         data:  yourJsonData,                     ...     }); } 

In my opinion, it makes for a clean and clear syntax, and avoids involving any global variables such as ajaxStart and ajaxStop, which could have unwanted side effects as your page develops.

If you don't know in advance how many ajax arguments you need to wait for (i.e. you want to use a variable number of arguments), it can still be done but is just a little bit trickier. See Pass in an array of Deferreds to $.when() (and maybe jQuery .when troubleshooting with variable number of arguments).

If you need deeper control over the failure modes of the ajax scripts etc., you can save the object returned by .when() - it's a jQuery Promise object encompassing all of the original ajax queries. You can call .then() or .fail() on it to add detailed success/failure handlers.

like image 131
Alex Avatar answered Oct 02 '22 06:10

Alex