0

Read the following code:

for (i = 0; i < 20; i++) {
  $.post( 'url', 'data='+ i, function (data) 
   {
      alert( 'Element ' + i + ' was added' );
   };
}

If you do this 20 POST will be performed at the same time!

What I need is to do this one by one (sequential)... How can I do that?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
CRISHK Corporation
  • 2,948
  • 6
  • 37
  • 52
  • First cycle i=0 POST receive data show alert(...), Second cycle i=1 POST receive data show alert( ... ), ... etc. – CRISHK Corporation Jul 27 '12 at 03:38
  • this is a duplicate question: http://stackoverflow.com/questions/5821380/how-to-make-a-jquery-post-request-synchronous – Mike Corcoran Jul 27 '12 at 03:39
  • @MikeCorcoran - Not sure the OP wants to make the code synchronous. He wants the AJAX to run sequentially, but the other code on the page does not have to wait for the AJAX to return. – Joseph Silber Jul 27 '12 at 03:40

1 Answers1

2

In the callback, simply call the function again.

function sendRequest(i) {
    $.post('url', 'data=' + i, function(data) {
        alert('Element ' + i + ' was added');

        if(i < 19) {
            sendRequest(i + 1);
        }
    });
}

sendRequest(0);
  • @JosephSilber: Regarding your second edit, I rolled it back for the following reasons: a. I find the prefix increment operator creates confusing code. It is unnecessary here, and no shorter when minified. b. The original code loops in the interval [0, 19] and so the correct conditional is `< 19`, not `< 20` (the increment occurs after the comparison). –  Jul 27 '12 at 04:40
  • You are right, I was wrong. As simple as that. Sorry for messing with your code. – Joseph Silber Jul 27 '12 at 05:42