I'm struggling with a call to a php script to save data to a mysql database. Basically I've created a loop to send (n) retrieved chunks of data to be saved. Each time only the last chunk is saved. However if I insert an alert() in onreadystatechange function I'm interrupting the script and all chunks get saved. Hence I deduct the loop is reiterating too quickly. Searching forums I've seen that by using setTimeout may help but not sure how to code this.

Can anyone help?

function saveFlights(){
var nb_grids = parseInt(document.getElementById('nb_grids').value);
var direction = "out";

for (i=1; i<=nb_grids; i++){

var output = createUrlString(i, direction);

if (xmlhttp){

xmlhttp.onreadystatechange = function(){

if (xmlhttp.readyState == 4 && xmlhttp.status == 200){
/*do something*/


function createUrlString(counter, direction){

/*script to produce output */