lvil lvil - 2 months ago 6
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) {
console.log(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?

Answer

You get a return value for each promise:

$.when.apply($, allPromises).done(function(returnData1, returnData2) {
    console.log(returnData1);
    console.log(returnData2);
});

see https://api.jquery.com/jquery.when/

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
    ...
};