EDIT: I just saw that these are synchronous requests. If you want to stick with synchronous requests, I think you want to check out this answer. I've never used the synchronous option, but I'm pretty sure you don't specify a callback function. If you don't mind switching to asynchronous, I think the code at the bottom of my answer would still work.
There are two places you are trying to append this content to the page. First, there's line 10:
$(item.data).appendTo("#content");
That should work just fine, assuming you write your condition how you like. The second place is the last line:
$(html).appendTo("#content");
This will fire before the content is loaded, appending a blank html string to the document. The trick is understanding that the AJAX requests, and this second appension, are executed immediately, but the success
function loading the results into the variable html
does not fire until the server sends back the requested information.
My answer for how to fix this depends on what kind of condition is being checked in line 9. If it's something detectable via event listeners, I would rewrite success
to do nothing but store the results in the global html
variable, then write a second event listener that fires when your condition is met, appending the contents of html
to your target and then clearing it. If, however, that condition cannot be detected with an event listener, I'd change your code to something like the following:
var html = "";
function loadByUrl(url) {
$.ajax({
url: url,
dataType: 'json',
success: function(json) {
$.each(json.data.children, function(i,item){
html += "<div>" + item.data + "</div>";
if( someCondition ) {
$(html).appendTo("#content");
}
});
});
}
loadByUrl("http://fake1.com");
loadByUrl("http://fake2.com");
loadByUrl("http://fake3.com");
If you want to be able to force it to append after you've finished loading fake3.com
, use closure to do something like:
var html = "";
function successFunction(force)
{
return function(json) {
$.each(json.data.children, function(i,item)
{
html += "<div>" + item.data + "</div>";
if (force || someCondition)
{
$(html).appendTo("#content");
}
});
};
}
function loadByUrl(url,force) {
$.ajax({
url: url,
dataType: 'json',
success: successFunction(force)});
}
loadByUrl("http://fake1.com",false);
loadByUrl("http://fake2.com",false);
loadByUrl("http://fake3.com",true); // true => force appension.