-1

My code:

    var test = getData(email, password, data.sites);
    console.log(test);  // 4 sites, 4 responses

// TODO if 4 responses, call other function

function getData(email, password, sites) {
    var formData = createFormDataArray(email, password, 0);     // not so relevant

    var returnValues = [];

    sites.forEach(function (site) {
        var url = 'http://' + site + '/test.php';
        var newValue;
        sendRequest(url, formData).done(function(value) {
            newValue = value.status;    // string
            console.log(newValue);
        });
        returnValues.push(newValue);    // add to array
    });

    console.log('------');
    console.log(returnValues); // print array
    return returnValues;
}

function sendRequest(url, formData) {
    return $.ajax({
        type: 'post',
        url: url,
        data: formData,
        crossDomain: true,
        dataType: 'json',
        encode: true
    });
}

What I want to do here is make multiple Ajax calls to different domains, put the results in an array.

If the array contains all the responses, I'd like to call another function, which I don't have right now.

The problem here is: the calls are asynchronous and I like to 'wait' until I receive all responses so that I can launch another function.

Currently is logged:


  • Empty array
  • Empty array
  • newValue: "Ok"

What I need:

  • newValue: "Ok"


  • ["Ok", "Ok", "Ok", "Ok"]

  • ["Ok", "Ok", "Ok", "Ok"]

Or something like this. How can this be done?

**Edit: My solution: **

var defers = [];
sites.forEach(function (site) {
    var url = 'http://' + site + '/test.php';
    var defer = sendRequest(url, formData);

    defers.push(defer);
});

$.when.apply(window, defers).always(function() {
    // the other function
});

Create an array of 'defers'. Then, use the solution from the answer below.

  • 1
    Possible duplicate of [Wait until all jQuery Ajax requests are done?](http://stackoverflow.com/questions/3709597/wait-until-all-jquery-ajax-requests-are-done) – JJJ Feb 24 '16 at 10:53
  • 1
    You can't return that array, you have to add a callback that is called inside the `.done` method. Also, all code that you want to happen after an AJAX call has to be added inside the success callback of the AJAX call itself (the done function) otherwise it will happen before the AJAX call. – XCS Feb 24 '16 at 10:54
  • I know that all code afterwards should be in the success callback, but I like to collect responses from multiple calls. –  Feb 24 '16 at 11:08

1 Answers1

0

You can use jQuery.when() to make multiple ajax calls and execute some function when all xhr calls are done.

$.when( $.ajax( "/page1.php" ), $.ajax( "/page2.php" ) ).done(function( a1, a2 ) {
  // a1 and a2 are arguments resolved for the page1 and page2 ajax requests, respectively.
  // Each argument is an array with the following structure: [ data, statusText, jqXHR ]
  var data = a1[ 0 ] + a2[ 0 ]; // a1[ 0 ] = "Whip", a2[ 0 ] = " It"
  if ( /Whip It/.test( data ) ) {
    alert( "We got what we came for!" );
  }
});

More detail can be found here

To use $.when() with for loop,

var returnValues = [];
var deferreds = [];
sites.forEach(function (site) {
        var url = 'http://' + site + '/test.php';
        deferreds.push(sendRequest(url, formData));
    });

$.when.apply($, deferreds).done(function(){
    for(var i=0; i<arguments.length; i++)
    {
        returnValues.push(arguments[i].status); 
    }
});
Siva
  • 2,735
  • 16
  • 14