How to get jquery to append output immediately after each ajax call in a loop

Posted by david_nash on Stack Overflow See other posts from Stack Overflow or by david_nash
Published on 2013-10-31T03:45:22Z Indexed on 2013/10/31 3:53 UTC
Read the original article Hit count: 94

Filed under:
|
|
|
|

I'd like to append to an element and have it update immediately. console.log() shows the data as expected but append() does nothing until the for loop has finished and then writes it all at once.

index.html:

...
<body>
    <p>Page loaded.</p>
    <p>Data:</p>
    <div id="Data"></div>
</body>

test.js:

$(document).ready(function() {
    for( var i=0; i<5; i++ ) {
        $.ajax({
            async: false,
            url: 'server.php',
            success: function(r) {
                console.log(r); //this works
                $('#Data').append(r); //this happens all at once

            }
        });
    }
});

server.php:

<?php 
    sleep(1);
    echo time()."<br />";
?>

The page doesn't even render until after the for loop is complete. Shouldn't it at least render the HTML first before running the javascript?

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about jQuery