Question

I am confounded as to how I am supposed to defer multiple AJAX requests and then run each request's callback function with its respective incoming AJAX data upon completion of all requests.

Any ideas?

Was it helpful?

Solution

If you really want to run nothing until all ajax calls have completed, then you need to install a completion function that just stores the completion parameters into an array of objects and when all have completed, you can just walk through the array and process each set of results.

// set numRequests to the total number of ajax requests you're doing
var numRequests = x;

// initialize results array
var results = [];

// use storeResults as your success handler for each ajax call
function storeResults(data, status, jqXHR) {
    results.push({data: data, status: status, jqXHR: jqXHR});
    if (results.length === numRequests) {
        // all results are in the array now, so process them all
    }
}

Or, if you have a separate completion handler for each ajax call and want to keep track of those, but still don't want to process any of them until all results are in, you can do it like this:

var results = [];
var numRequests = 0;
function addCompletionHandler(fn) {
    ++numRequests;
    return function(data, status, jqXHR) {
        // store the response data
        results.push({data: data, status: status, jqXHR: jqXHR, fn: fn});

        // if all requests are done, then process them all by calling all their
        // success handlers one after another
        if (results.length === numRequests) {
            for (var i = 0; i < results.length; i++) {
                var item = results[i];
                item.fn(item.data, item.status, item.jqXHR);
            }
        }
    };
}

// make multiple ajax calls
// all completion handlers will be called only when all the ajax calls have finished
$.ajax({type: 'POST', 
        url: 'whatever1.php', 
        data: whatever1, 
        success: addCompletionHandler(function(data, status, jqXHR) {
            // completion handler for this ajax call
        })
});
$.ajax({type: 'POST', 
        url: 'whatever2.php', 
        data: whatever2, 
        success: addCompletionHandler(function(data, status, jqXHR) {
            // completion handler for this ajax call
        })
});
$.ajax({type: 'POST', 
        url: 'whatever32.php', 
        data: whatever3, 
        success: addCompletionHandler(function(data, status, jqXHR) {
            // completion handler for this ajax call
        })
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top