Actually, what your code does is not far from a Denial of Service attack on your own server :)
The Ajax requests won't block until they are finished, as the others already pointed out. Calling $.ajax
returns immediately, the actual request is executed in the background and calls the success
callback upon completion. This all means that Javascript loops through the while
as fast as it can, because nothing stops it. This also means that while your first request tries to finish, Javascript has probably spawned thousands of new requests which all need to be processed by the server.
Your server will become uncomfortable serving so many requests at the same time and slows down (if you check it's CPU and memory usage, you will notice). Because of the server slowing down Javascript will spawn ever more and more requests... until finally the whole system grinds to a halt because Javascript is running out of resources and your server probably, too.
A while
loop is not recommended in your case. It's better to send one request at a time and check for the return value inside the success
callback. If it's not 0 yet, spawn another request, and repeat the procedure.
function updateRows(onCompleted) {
$.ajax({
url: '/ajax.php?updateRow='+hasData,
dataType: 'json',
success: function(data) {
hasData = data.next;
if (hasData == 0) {
return onCompleted();
}
$('.result').append(data.html);
updateRows(onCompleted); // not finished yet, recursion
}
});
}
The onCompleted
argument would be a callback function that gets executed once your update procedure is completed. You could use it as follows:
updateRows(function() {
// Now all rows are updated
// Proceed with program flow
});