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?
Simple change using jQuery-ajax’s complete property: