0

i want to make multiple ajax requests using jQuery that appends table rows into a table but i want their response in order

for (i=0;i<5;i++) {
    //variables tempString, start_value updated here after every loop iteration

    $.post(
        'results.php',
        {start_value:start_value,tempString:tempString},
        function(data3){
            // alert(data3);
            $('#data_table tbody tr:last').after(data3);
        }
    );

}

results.php returns a set of table rows with every request but they dont append to the table in the right order.

how do I make the next ajax requests wait till the first ones are finished?

null void
  • 31
  • 4
  • 1
    http://jsfiddle.net/zhjx89Lf/1/ – Umesh Sehta Mar 11 '15 at 05:54
  • Possible duplicate of http://stackoverflow.com/questions/5821380/how-to-make-a-jquery-post-request-synchronous – peterdotjs Mar 11 '15 at 06:00
  • chrome gives a warning on using synchronous ajax saying that it can hinder with user experience. Infact, i tried it before posting this question, but it would freeze my page till all the responses were not received. – null void Mar 11 '15 at 11:16

1 Answers1

0

You need to synchronus call and in your case it call asynchronously thats why it not append in right order.

function doAsyncCall(i) {
    if (i < 5) {
       $.post(
        'results.php',
        {start_value:start_value,tempString:tempString},
        function(data3){
            $('#data_table tbody tr:last').after(data3);
            doAsyncCall(i+1);
        }
      );
    }
}

doAsyncCall(0);
Sadikhasan
  • 18,365
  • 21
  • 80
  • 122