Reputation: 301
I'm having some issues where the dom is only updated once the $.each loop has completed.
On my page I have a number of divs which when looped over has a orange color applied to it, when the data is posted to the server if the response is 200 the div color is changed to green otherwise it is changed to red.
The issue with the script is that the dom isn't updated, the color is always orange/pending. If I remove that bit of code then the items do turn green/complete, but only after each ajax call has completed.
How can I get the dom to update after each $.ajax call? Thanks
$.each(csv_ids , function( i , val ) {
$('#item_' + val).addClass('csv_pending_item_pending');
$.ajax({
url: '/foo' ,
type: 'POST' ,
async: false,
data: { csvID : val } ,
error : function() {
console.log('error');
},
success: function(data) {
$('#loop_upload_item').html(val);
console.log(data)
if(data.response == '200') {
$('#item_' + val).addClass('csv_pending_item_complete');
console.log('#item_' + val + ' good')
}else{
$('#item_' + val).addClass('csv_pending_item_error');
}
}
}); // ajax
}); // each
Upvotes: 1
Views: 2040
Reputation: 10836
The browser will only repaint when your javascript stops executing. Because you're not using asynchronous requests it doesn't stop and the repaint only happens at the very end, after all the requests have completed.
If you remove async: false,
I would expect it to work as you want. However, as you say you want to stagger the upload process you need to trigger the next upload to start when the previous one completes.
Something like the following should work. You'll see that we look through each id and create a function to do the upload for that id. At the end of the success function we call the next function in the chain.
var upload_func= function () { };
for(var val in csv_ids) {
var next_func = upload_func;
upload_func= function() {
$('#item_' + val).addClass('csv_pending_item_pending');
$.ajax({
url: '/foo' ,
type: 'POST',
data: { csvID : val } ,
error : function() {
console.log('error');
},
success: function(data) {
$('#loop_upload_item').html(val);
console.log(data)
if(data.response == '200') {
$('#item_' + val).addClass('csv_pending_item_complete');
console.log('#item_' + val + ' good')
}else{
$('#item_' + val).addClass('csv_pending_item_error');
}
next_func();
}
}
}
}
upload_func();
Upvotes: 1