Wait until all jQuery Ajax requests are done?

javascript wait until ajax request is finished
wait for ajax response before continuing javascript
two ajax calls on one click
multiple ajax calls promise
multiple ajax calls in loop
how to stop multiple ajax requests
jquery multiple ajax calls
jquery each wait until complete

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?

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.

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  Waiting Until All jQuery Ajax Requests are Done In this tutorial, we will answer to your question of making the function wait until all Ajax requests are done. jQuery provides when() function which will solve this problem accepting any number of Deferred objects as arguments, and executing a function when all of them resolve.

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

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

In this case, there is no need to guess how many requests can be in an application that might finish in the future. In some cases ajax requests can be part of a function's inner logic, which can be quite complicated (e.g. calling other functions), and in that case, you might not wait until said function is done with its entire logic rather than only waiting for the ajax part to complete.

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

Again the purpose of this handler is to know when there is no active ajax not to clear or reset something.

P.S. If you don't mind using ES6 syntax, then you can use Promise.all for known ajax methods. Example:

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 jsFiddle demonstrating the last one.

Multiple Simultaneous Ajax Requests (with one callback) in jQuery , done(function() { // Ajax success });. But we have three Ajax requests we're needing to perform, and we want to wait for all three of them to finish before  If you want to wait until 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 there is no need to guess how many requests can be in an application that might finish in the future.

I found a good answer by gnarf my self which is exactly what I was looking for :)

jQuery ajaxQueue

//This handles the queues    
(function($) {

  var ajaxQueue = $({});

  $.ajaxQueue = function(ajaxOpts) {

    var oldComplete = ajaxOpts.complete;

    ajaxQueue.queue(function(next) {

      ajaxOpts.complete = function() {
        if (oldComplete) oldComplete.apply(this, arguments);

        next();
      };

      $.ajax(ajaxOpts);
    });
  };

})(jQuery);

Then you can add a ajax request to the queue like this:

$.ajaxQueue({
        url: 'page.php',
        data: {id: 1},
        type: 'POST',
        success: function(data) {
            $('#status').html(data);
        }
    });

Wait until all the jQuery Ajax requests are done?, In short, I need to wait for all Ajax requests to complete before executing the next request. But how? #1 building A small solution is this: // Define  If you want to wait until all ajax requests are finished in your document, no matter how many of them exist, just use $.ajaxStop event this way: $(document).ajaxStop(function () { // 0 === $.active }); In this case, there is no need to guess how many requests can be in an application that might finish in the future.

Use the ajaxStop event.

For example, let's say you have a loading ... message while fetching 100 ajax requests and you want to hide that message once loaded.

From the jQuery doc:

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

Do note that it will wait for all ajax requests being done on that page.

jQuery.when(), For example, the jqXHR object returned by jQuery.ajax() is a Promise-compatible The method will resolve its master Deferred as soon as all the Deferreds resolve, for a complete description of success and error cases for an ajax request). Wait for async ajax requests to finish. Ask Question Asked 6 years, 9 months ago. Active 2 years, 8 months ago. Wait until all jQuery Ajax requests are done? 764.

NOTE: The above answers use functionality that didn't exist at the time that this answer was written. I recommend using jQuery.when() instead of these approaches, but I'm leaving the answer for historical purposes.

-

You could probably get by with a simple counting semaphore, although how you implement it would be dependent on your code. A simple example would be something like...

var semaphore  = 0,     // counting semaphore for ajax requests
    all_queued = false; // bool indicator to account for instances where the first request might finish before the second even starts

semaphore++;
$.get('ajax/test1.html', function(data) {
    semaphore--;
    if (all_queued && semaphore === 0) {
        // process your custom stuff here
    }
});

semaphore++;
$.get('ajax/test2.html', function(data) {
    semaphore--;
    if (all_queued && semaphore === 0) {
        // process your custom stuff here
    }
});

semaphore++;
$.get('ajax/test3.html', function(data) {
    semaphore--;
    if (all_queued && semaphore === 0) {
        // process your custom stuff here
    }
});

semaphore++;
$.get('ajax/test4.html', function(data) {
    semaphore--;
    if (all_queued && semaphore === 0) {
        // process your custom stuff here
    }
});

// now that all ajax requests are queued up, switch the bool to indicate it
all_queued = true;

If you wanted this to operate like {async: false} but you didn't want to lock the browser, you could accomplish the same thing with a jQuery queue.

var $queue = $("<div/>");
$queue.queue(function(){
    $.get('ajax/test1.html', function(data) {
        $queue.dequeue();
    });
}).queue(function(){
    $.get('ajax/test2.html', function(data) {
        $queue.dequeue();
    });
}).queue(function(){
    $.get('ajax/test3.html', function(data) {
        $queue.dequeue();
    });
}).queue(function(){
    $.get('ajax/test4.html', function(data) {
        $queue.dequeue();
    });
});

Waiting For Multiple Ajax Requests - jQuery, Write jQuery code to wait for multiple Ajax requests. The page enables user interaction only after the page gets all data. For example, the done method can be used as the success callback function for a jqXHR object. If you refer to jQuery.When doc, if one of your ajax call fails, fail master callback will be called even if all following ajax call haven't finished yet. In this case you are not sure that all your calls are finished. If you want to wait for all your calls, no matter what the result is, you must use another Deferred like this :

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  In the case where multiple Deferred objects are passed to jQuery.when (), the method returns the Promise from a new "master" Deferred object that tracks the aggregate state of all the Deferreds it has been passed. The method will resolve its master Deferred as soon as all the Deferreds resolve, or reject the master Deferred as soon as one of

jquery wait for all ajax requests to complete Code Example, Get code examples like "jquery wait for all ajax requests to complete" instantly right from your google search results with the Grepper Chrome  Wait Until Loop of jQuery AJAX Requests are Done I have an application that requires a set of search results to be flagged if the user selects a checkbox in front of the each search result item. I use an each( ) loop to set the flag of each search result item via an AJAX call.

Call function after all ajax requests complete : javascript, var booksAvailable = {}; for (var i = 0; i < books.length; i++) { $.ajax('/books/' + books[i], Now let's ignore the various issues with throwing out a bunch of ajax requests at Of course, many will say use jQuery's when(), but this is of no use to me. I'm not sure I see how this helps me with waiting for a group of ajax calls to​  All three requests in parallel wait for all three to be done go. We can use a bit of Deferred / Promises action to help here. I'm sure this is some JavaScript 101 stuff to some of you but this kind of thing eluded me for a long time and more complex Promises stuff still does. In our simple use case, we can use jQuery's $.when () method

Comments
  • How are you calling your original ajax requests?
  • What do you mean by "done" ? I understand it as "all requests have finished either successfully or not" (resolved or rejected). But you may mean "all requests have finished successfully" (resolved). see all the variations in api.jquery.com/category/deferred-object
  • This should be marked as a correct answer because it's simple, efficient and works great. Also, it should be noted that $.when returns a Promise object which has more useful methods, not only .done. For example, with .then(onSuccess, onFailure) method you could react when both requests succeed or at least one of them fails.
  • Is it possible to bunch the requests ajax1..4 into an array and pass that?
  • Be careful with the fail case. Unlike done, fail fires immediately on the first fail and disregards the remaining deferreds.
  • @skalee thanks for highlighting the fact that an onFailure function could be attached. As I pointed out in a comment to the OP's question: he might want to indicate more precisely what he meant by "done". "Ryan Mohr" did also have a very good point regarding the fact that fail behaves differently as done, some further reading to be done about Promises I guess html5rocks.com/en/tutorials/es6/promises
  • It is great to give people exposure to the when method, and to promises in general, but I think this isn't the best answer. If any of those ajax functions anywhere down the line create another ajax request, and then don't integrate that new promise into the chain correctly... those requests will escape this technique. For example, I can't use this technique without modifying the Shopify library I'm using for ajax add-to-cart behaviour, because it wasn't written in a 'promisy' way, and never returns the xhr objects it creates. Does this make sense? Still a great answer, though!
  • +1 Much better than other answers in case you have to deal with 3rd party scripts with anonymous callbacks/closures.
  • @kaiser Valid point but it's not what the question was asking. It's not very good if you don't want to wait for all AJAX calls to return. The question is specific about waiting for the AJAX calls you've made on your own (called inside another function, as the OP wrote). Some other code may have made another AJAX call that you don't want to wait for.
  • Compared to the when() solution, it has the advantage to work even if the number of ajax calls is not known.
  • Compared to the when() solution, it has the large disadvantage not to work well together with other components, since it shares a document-wide global state. If there is some long polling going on continuously, it might even never fire.