Lioo
Lioo

Reputation: 395

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

Upvotes: 4

Views: 120

Answers (2)

choz
choz

Reputation: 17898

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

Upvotes: 4

onzinsky
onzinsky

Reputation: 591

I believe you need to use .done(...).

Check this to learn the differences.

edit

As per the docs of jquery, if you pass NOT-a-promise to the .when(...) method, the .then(...) will get called automatically and treat the arguments you passed to .when(...) as already resolved promises, and also pass them to the .then(...)

So, the array you're passing have to be promises so that the .when(...) gets called at the correct time.

If a single argument is passed to jQuery.when() and it is not a Deferred or a Promise, it will be treated as a resolved Deferred and any doneCallbacks attached will be executed immediately.

Check docs.

edit 2

I thought your ajaxRequisitions methods were already working. Here's the example from the docs to the .when(...) function

$.when( $.ajax( "test.aspx" ) ).then(function(
        data, textStatus, jqXHR ) {
    alert( jqXHR.status ); // Alerts 200
});

You need to update it so you can add the .apply(...), and have your ajaxRequisition... Methods return the Ajax call you need in each one.

Upvotes: 2

Related Questions