ADT
ADT

Reputation: 141

jQuery.when() statement prematurely occuring before ajax calls finished

Trying to use jquery and ajax to change a message printed out initially on my page:

document.write('<p align="center" id="DataReady">Waiting for server to update the table</p>');

to something else once all of the ajax calls are made and my data is updated. The general outline of my code is as follows:

function getData(m) {

    jqs[m] = $.ajax({
        url : WebURL[m],
        type : 'GET',
        dataType: 'jsonp',
        myJ : m
    });
    return jqs[m];
}


function handleData(json_data){

    var j = this.myJ;

    // Inside this function, I manipulate the json_data 
    // object and store it into other variables
}   

$(document).ready(function() { 

    for (var i=0; i<5; i++){
        getData(i).done(handleData); 
    }

    $.when(jqs).done(function(){
        document.getElementById("DataReady").innerHTML = "Up to date!"
    });
});

When the document is ready, I am basically looping through my getData function and executing ajax calls using deferred objects, and when each respective ajax call is done, the handleData function takes the json data (specific to each respective ajax call) and manipulates it for further use.

However, once I loop through all of the ajax calls (which are stored in the jqs array), I can't seem to make the last part work correctly: my $.when statment. I have reviewed the jquery API (http://api.jquery.com/jQuery.when/) and can't seem to see what I'm doing wrong.

What I want to have happen with the last statement is for when all the ajax calls are made (stored in the array jqs), the initial message to change to "Up to date!", but not any sooner. It seem right now that the message is getting changed to "Up to date!" even though the ajax calls aren't done. Further troubling is that if I delete the line getData(i).done(handleData); the message still gets changed even though no ajax calls have occurred. Does anyone have any idea on how to fix this? Any constructive help is greatly appreciated. Thanks.

Upvotes: 1

Views: 109

Answers (1)

SLaks
SLaks

Reputation: 887449

$.when() doesn't take an array.
When you pass an array (even if it's an array of promises), jQuery treats it as a resolved value.

To pass multiple promises, you need to call .apply to pass each one as a separate argument:

$.when.apply($, jqs).done(...);

Upvotes: 4

Related Questions