I’m trying to execute an Ajax function in a loop and I want that my loop go to next instruction only when the ajax call finishes. I’ve tried to put the ajax async to false, but my loading message didn’t appear and my screen refreshs when all iterations of the loop finish. If async is set to true it executes all together at the same time.
Here’s my code:
function pingAll( url )
{
var arrIDs = new Array();
var pattern = /[0-9]+/g;
$("input:checkbox[name=checkbox-router]:checked").each(function()
{
var strCheckboxID = $(this).attr( 'id' );
var routerID = strCheckboxID.match( pattern );
arrIDs.push( routerID );
});
for (var i in arrIDs)
{
pingRouter(url + arrIDs[i], arrIDs[i]);
}
}
function pingRouter( url, shortID )
{
$( '#ping-resp-' + shortID ).html( 'Loading...' );
var pingRequestTimeout = $( '#pingRequestTimeout' ).val();
url = url + "?timeout=" + pingRequestTimeout;
$.ajax
({
url: url,
async: true,
success: function( data )
{
var objData = $.parseJSON( data );
var response = objData.response.replace(/(\r\n|\n|\r)/gm,"")
.
.
.
var latency = parseFloat( objData.latency );
$( '#ping-resp-' + shortID ).html( latency + ' ms' );
}
});
return;
}
Thanks for your help.
You could use recursion as follows:
And change your calling function to:
See API for always.