Reputation: 1
I'm trying to update a list after getting some data from an ajax call. It works something like this
$.ajaxSetup({
async: false
});
$.ajax(jsonUrl, {
dataType: "json",
success: function(data) {
$.each(data.list, function(k,v) {
addOutput("doing something with "+v);
(...)
}
},
(...)
});
$.ajaxSetup({
async: true
});
addOutput:
function addOutput(text, color) {
color = typeof color !== 'undefined' ? color : '#fff';
var date = new Date();
var h = ("0"+date.getHours()).slice(-2);
var m = ("0"+date.getMinutes()).slice(-2);
var s = ("0"+date.getSeconds()).slice(-2);
var li = "<li style='background-color: "+color+"; padding: 2px; pading-left: 3px;'>"+h+":"+m+":"+s+" - "+text+"</li>"
$("#output_list").prepend(li);
}
addOutput(text) is adding a new <li> element to an output console but this is where my problem is. The output console doesn't update immediately instead it updates after jQuery.each is done.
I'm stopping async here because there is another ajax call in the loop to send some requests depending on the list but that's not the problem i guess because i already tested the output without it. So i think it has something to do with jQuery.each?
Update: Added addOutput
Upvotes: 0
Views: 692
Reputation: 5992
you might want to do this...
$.ajax(jsonUrl, {
dataType: "json",
success: function(data) {
$.each(data.list, function(k,v) {
addOutput(v); // instead of text, you want to output v. k is index and v is the actual result element
}
},
...
});
EX:
<div class="add"></div>
var result = [1, 2, 3, 4, 5, 6, 7, 8, 9];
var index = 0;
$.each(result, function () {
show();
debugger;
});
function show() {
$('.add').append("<h1>" + index + "</h1>");
index += 1;
}
you will find debugger stops while lopping through and adding each element to DOM.
Upvotes: 1
Reputation: 1
If i'm not wrong, success will only be called when the request has the complete response, so it's not an issue, so if you want to cause the impression off a loading list, you'll probably have to do some code with waits for every .each.
Why are you disabling async? This makes the browser do the request without getting the user an stuck screen.
Regards,
Upvotes: 0