lvil lvil - 8 months ago 37
jQuery Question

How to get all returned data from all ajax calls when all done?

I have two jquery ajax calls.

After all calls are complete, I want to get both returned data.

For the example purpose both return "num".

Here is my code:

$(document).ready(function () {
var allPromises = [
$.ajax({url: '/ajax.php', method: 'post', data: {num: 1}}),
$.ajax({url: '/ajax.php', method: 'post', data: {num: 2}})

$.when.apply($, allPromises).done(function(returnData) {

For instance, I want to get sum of the returned values.

The problem is that I am getting data only from the first request.

How can I do it without saving in global variable?


You get a return value for each promise:

$.when.apply($, allPromises).done(function(returnData1, returnData2) {


For an unknown number of ajax calls you can use:

$.when.apply($, allPromises).then(function() {
    var objects = arguments; // The array of resolved objects as a pseudo-array