javamonkey79 javamonkey79 - 2 months ago 8
Javascript Question

jquery collect from multiple ajax calls

I am trying to use jquery and ajax to collect data from several url's and then create content from that. However, I must be missing something as it does not seem to work.

I have something like this:

var html = "";
function loadByUrl(url) {
$.ajax({
url: url,
dataType: 'json',
async: false,
success: function(json) {
$.each(json.data.children, function(i,item){
if( someCondition ) {
$(item.data).appendTo("#content");
} else {
html += "<div>" + item.data + "</div>";
}
}
}
});
}

loadByUrl("http://fake1.com");
loadByUrl("http://fake2.com");
loadByUrl("http://fake3.com");
$(html).appendTo("#content");


Basically, if some condition is met then I will add the content immediately, otherwise I'd like to add it at the end of the content with all of the other "saved off" content.

Is what I'm trying to do possible? If so, how?

Answer

New answer:

I would approach this problem differently. Instead of using async: false, which is generally frowned upon (it's even deprecated in the latest version of jQuery), I would use $.when to achieve the same affect.

// return a promise
function loadByUrl(url) {
    return $.ajax({
        url: url, 
        dataType: 'json'
    });
}

// handle processing the data in a separate function
function processData(data) {
    var result = '';
    $.each(data.children, function(i,item){
        if( someCondition ) {
             $(item.data).appendTo("#content");
        } else {
            result += "<div>" + item.data + "</div>"; 
        }
    }
    return result;
}

// use when to ensure all of the AJAX requests execute before
// doing anything with their results
$.when(loadByUrl("http://fake1.com"), loadByUrl("http://fake2.com"), loadByUrl("http://fake3.com")).done(function(fake1, fake2, fake3) {
    // this function is called after all three AJAX promises are resolved
    var html = '';

    html += processData(fake1[0]);
    html += processData(fake2[0]);
    html += processData(fake3[0]);

    $(html).appendTo("#content");
});

Original answer:

The issue is $.ajax is asynchronous. Try replacing this line:

html += "<div>" + item.data + "</div>";

With this:

$("<div>" + item.data + "</div>").appendTo("#content");