Space Bear Space Bear - 4 months ago 7
Ajax Question

javascript code not executing in order

So I'm trying to fetch data from a server in json format.

with this code

for (var i = 0; i < hosts.length; i++) {
var tempUrl = url + hosts[i];
jQuery.ajax({
type : "GET",
dataType : "json",
username : "user",
password : "password",
url : url,
async : true,
success : function (data) {
//var obj = data.data.host.status;
//console.log(obj);
jsonHosts.push(data.data);
console.log("added data");
}
});
}


followed by this code block

for (var i = 0; i < jsonHosts.length; i++) {
console.log("dog");
console.log(jsonHosts[i].host.status);
document.getElementById('test').innerHTML += "<br>" + jsonHosts[i].host.status;
document.getElementById('test').innerHTML += '<br>Some new content!';
}
console.log("done");


problem is, my console will show "done" then "added data" and my webpage will be blank.

I've tried putting the first section in a function and trying to get my code to wait for the function to finish executing but to no avail.

anyway I can make this code execute in order/have the second block wait on the first block

Answer

Move below portion of code into success callback function

success : function (data) {
    //var obj = data.data.host.status;
    //console.log(obj);
    jsonHosts.push(data.data);
    for (var i = 0; i < jsonHosts.length; i++) {
        console.log("dog");
        console.log(jsonHosts[i].host.status);
        document.getElementById('test').innerHTML += "<br>" +     jsonHosts[i].host.status;
        document.getElementById('test').innerHTML += '<br>Some new content!';
    }
    console.log("done");
}
Comments