3

I need to make a number of ajax calls(the exact number is variable) and wait for them all to complete. My current code is as follows:

ajaxRequests = new Array();

ajaxRequests.push(function(){
                return jQuery.post(url: "someUrl",
                                    dataType: "json",
                                    data:  yourJsonData
            });



jQuery.when.apply(jQuery, ajaxRequests).done(function(){
    alert("ajax requests done");
});

Unfortunatly the above code is not waiting for the ajax request to finish. Any help would be apprecited.

Erik Philips
  • 53,428
  • 11
  • 128
  • 150
FredTheLover
  • 1,009
  • 10
  • 19
  • 1
    check if the following answer may help you http://stackoverflow.com/questions/9865586/jquery-when-troubleshooting-with-variable-number-of-arguments – mrida Jun 26 '13 at 20:42
  • Make sure you close the parenthesis after yourJsonData. It may be causing the problem – mrida Jun 26 '13 at 20:51

1 Answers1

4

The answer is below: Copied from jQuery .when troubleshooting with variable number of arguments

// Array of requests
var requests = Array();
requests.push($.get('responsePage.php?data=foo'));
requests.push($.get('responsePage.php?data=bar'));

var defer = $.when.apply($, requests);
defer.done(function(){

    // This is executed only after every ajax request has been completed

    $.each(arguments, function(index, responseData){
        // "responseData" will contain an array of response information for each specific request
    });

});
Community
  • 1
  • 1
FredTheLover
  • 1,009
  • 10
  • 19
  • 2
    This works well when you have at least two requests to send. Otherwise you get an inconsistent behavior when it's one query or several :( – Happynoff Sep 29 '16 at 11:26