Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the ajax results for multiple deferred calls in jquery?

I am trying to get the jquery deferred work as shown in the code below.

<script type="text/javascript">
    var appUrls = {
                      GetDataUrl : '@Url.Action("GetData")'
                  };

    function GetData1(){
        return $.getJSON(appUrls.GetDataUrl, { Id: 1 });
    }

    function GetData2() {
        return $.getJSON(appUrls.GetDataUrl, { Id: 2 });
    }

    $(function(){
        $("#result").html("Getting Data1, Data2 .... ");

        $.when(GetData1(), GetData2())
         .then(function(result){
             //The 'result' only contains the data from first request.  
             console.log(result);
             $("#result").html("Completed GetData1, GetData2"); 
         });

    });

    </script>

After both calls are completed I would like to extract the Json data returned from both the calls. However, the 'result' object only contains the data returned by the first call (GetData1)? How can I get the result for both the calls in the 'then' callback method above.

like image 545
Amitabh Avatar asked Feb 21 '11 13:02

Amitabh


1 Answers

Since you have two requests you'll get two arguments result1,result2:

<script type="text/javascript">
var appUrls = {
    GetDataUrl : '@Url.Action("GetData")'
};

function GetData1(){
    return $.getJSON(appUrls.GetDataUrl, { Id: 1 });
}

function GetData2() {
    return $.getJSON(appUrls.GetDataUrl, { Id: 2 });
}

$(function(){
    $("#result").html("Getting Data1, Data2 .... ");

    $.when(GetData1(), GetData2())
    .then(function(result1,result2){
        console.log(result1);
        console.log(result2);
        $("#result").html("Completed GetData1, GetData2"); 
    });

});

</script>
like image 185
ifaour Avatar answered Sep 20 '22 06:09

ifaour