Lioo Lioo - 5 months ago 6
jQuery Question

Using $.when with Ajax requisitions

I want to execute some $.ajax() requisitions in a certain order, so I tried to use $.when like this:(just for testing)

$.when.apply(null,[ajaxRequisition1(),ajaxRequisition2()] ).then(function () {
console.log("Completed all requests.");
});


But it shoots the message on the console before the requisitions are done. Any suggestions?

Thanks

EDIT

Here are one of my requisitions. I'll post one, but the others are very similar, changing only some parameters.

code:

function ajaxRequisition1(){
$.ajax({
type:'GET',
crossDomain:true,
url:'http://www.myurl.com.br/api/my_php.php?callbackplat=?',
dataType:'jsonp',
data: {currency: $('#cur').val()},
beforeSend: function(){
$('#loading').css("display","block");
$('table[name=tb_latam]').css("opacity","0.01");

}

}).done(function(data){
console.log(data);
//HERE I BUILD A TABLE USING THE DATA RECEIVED.

$('#loading').css("display","none");
$('table[name=tb_latam]').css("opacity","1");


$('#tb_latam').append('<tr> <td data-nome="A-ACTIVE" class="column_st">'+'Active'+
'</td><td class="c_qtdA column_qtd">'+data.lat_qtdA+
'</td><td id="a2"class="a">'+data.lat_active+
'</td><td>'+data.lat_p_active+'</td></tr>');


$('#tb_latam').append('<tr> <td data-nome="I-INACTIVE" class="column_st">'+'Inactive'+
'</td><td class="c_qtdI column_qtd">'+data.lat_qtdI+
'</td><td class="i">'+data.lat_inactive+
'</td><td>'+data.lat_p_inactive+'</td></tr>');

$('#tb_latam').append('<tr> <td data-nome="R-REPLACED" class="column_st">'+'Replaced'+
'</td><td class="c_qtdR column_qtd">'+data.lat_qtdR+
'</td><td class="r">'+data.lat_replaced+
'</td><td>'+' - '+'</td></tr>');

})
.fail(function(data, textStatus, errorThrown){
alert("ERROR!.");
console.log(data);
console.log(textStatus);
console.log(errorThrown);
});
return false;
}

Answer

jQuery $.when() accepts deferred objects. While your ajaxRequisition returns a non deferred, $.when() will then return a resolved promise.

Try to change your code,

function ajaxRequisition1 () {
    return $.ajax({
        ...
    });
}

function ajaxRequisition2 () {
    return $.ajax({
        ...
    });
}

$.when.apply(null, [ajaxRequisition1(),ajaxRequisition2()]).done(function () {
    console.log("Completed all requests.");
});
Comments