JQuery every / ajax does not update the loop elements

advertisements

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


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
          }
        },
        ...
});

Fiddle DEMO

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.