2

Possible Duplicate:
Multiple ajax calls inside a each() function.. then do something once ALL of them are finished?

How do I execute a function after I run ajax in for loop. Example here I have this ajax running in loop,

for (var countDevice = 0; countDevice<32; countDevice++){
  var dataString="modbus="+(countDevice+1)+"_"+newDate+".xml";
  $.ajax({
    type: "POST",
    url: "CalculateTable",
    data: dataString,
    dataType: "json", 
    //if received a response from the server
    success: function( device, textStatus, jqXHR) {
     //Do something                                 
    }
  });
}

I want to make sure to only run this function below, only after the above for loop is finished.

function drawTable(){
  //Do something
}

Can anyone give any idea on how to make it possible? Thanks for taking the time to read and answer.

Community
  • 1
  • 1
Nur
  • 111
  • 2
  • 12

3 Answers3

2

if u want to running it in the linear way, u can write your code like this

var countDevice = 0;
(function CountDeviceLoop() {
  if (countDevice == 32) {
    // you can place draw table here or .....
    // drawTable();
    return;
  }

  var dataString="modbus="+(countDevice+1)+"_"+newDate+".xml";
  $.ajax({
    type: "POST",
    url: "CalculateTable",
    data: dataString,
    dataType: "json", 
    //if received a response from the server
    success: function( device, textStatus, jqXHR) {
      //Do something


      //after done sth
      countDevice ++;
      CountDeviceLoop();                             
    }
  });
})();

// here
// drawTable();

cuz the ajax method is async, u can run your loop in this way...or if u want to use 'for loop' to run your program, you can use @MadSkunk 's code

KiddKai
  • 21
  • 3
0
for (var countDevice = 0; countDevice<=32; countDevice++)
{
if (countDevice == 32)
{
drawTable();
}
else {
var dataString="modbus="+(countDevice+1)+"_"+newDate+".xml";
$.ajax({
type: "POST",
url: "CalculateTable",
data: dataString,
dataType: "json",

//if received a response from the server
success: function( device, textStatus, jqXHR) {
//Do something
}
});
}
}
Muhammad Talha Akbar
  • 9,952
  • 6
  • 38
  • 62
-1

Yoo can also try

$('your selector').ajaxComplete(function() {
  drawTable();
}); 
softsdev
  • 1,478
  • 2
  • 12
  • 27