punkish
punkish

Reputation: 15248

combining results from several ajax requests

I have several ajax requests that return different values (pseudocode ahead)

var foo = "", bar = "", result = "";

$.ajax({
    url     : url1,
    type    : "GET",
    data    : data,
    dataType: "json",
    success : function(res) {
        foo = "number of foo: " + res.foo;  
    }
});

$.ajax({
    url     : url2,
    type    : "GET",
    data    : data,
    dataType: "json",
    success : function(res) {
        bar = "number of bar: " + res.bar;  
    }
});

and so on. I want to fire these requests, and then combine the results and present them to the user

result = foo + "\n" + bar;

Of course, since the requests are asynchronous, there is no guarantee that by the time my code is ready to display result that foo and bar will be available. I could hack something like so

$.ajax({
    url     : url1,
    type    : "GET",
    data    : data,
    dataType: "json",
    success : function(res) {
        result = "number of foo: " + res.foo + "\n";

        $.ajax({
            url     : url2,
            type    : "GET",
            data    : data,
            dataType: "json",
            success : function(res) {
                result += "number of bar: " + res.bar;
                alert(result);
            }
        });
    }
});

But, that doesn't seem right. Suggestions on a better way to solve this?

Upvotes: 0

Views: 245

Answers (2)

Felix Kling
Felix Kling

Reputation: 816422

You can make use of the fact that the jqXHR object returned by the Ajax methods is a deferred object. Together with $.when [docs], you can do:

$.when($.get(url1, data), $.get(url2, data)).done(function(a1, a2) {
    var result1 = $.parseJSON(a1[2].responseText),
        result2 = $.parseJSON(a2[2].responseText),
        result = "number of foo: " + result1.foo + " number of bar: " + result2.bar;

    // do other stuff
});

Upvotes: 3

Shad
Shad

Reputation: 15451

Simple change using jQuery-ajax's complete property:

var foo = "", bar = "", result = "", comp1=false, comp2=false;

$.ajax({
    url     : url1,
    type    : "GET",
    data    : data,
    dataType: "json",
    success : function(res) {
        foo = "number of foo: " + res.foo;  
    },
    complete: function(){
        comp1=true;
        comp1 && comp2 && triggerSomeEvent();
    }
});

$.ajax({
    url     : url2,
    type    : "GET",
    data    : data,
    dataType: "json",
    success : function(res) {
        bar = "number of bar: " + res.bar;  
    },
    complete: function(){
        comp2=true;
        comp1 && comp2 && triggerSomeEvent();
    }
});

function triggerSomeEvent(){//Handles completed `result`
   result = foo + "\n" + bar;
   //End then...
}

Upvotes: 3

Related Questions