CRISHK Corporation
CRISHK Corporation

Reputation: 3008

How to do a for cycle with post in jquery

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?

Upvotes: 0

Views: 229

Answers (1)

user1479055
user1479055

Reputation:

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);

Upvotes: 2

Related Questions