egig
egig

Reputation: 4430

Consecutive Jquery Ajax post

This code I've created:

    $("button").click(function(){
       for (var i=0;i<array.length;i++){
         var text = array[i];
         $.post("process.php",
                { data : text},
                function(data){
                  if (data="success"){
                   alert("success");
                 } else {
                   alert(data);}
         });
       }
    });

is work but doesn't send data (text) consecutively according to array index. I can't send it one by one because array length will be inputted by user. How to make ajax post consecutively according to its index of array of it's data? and, this is the important too, how do I detect onComplete() event on the last request?. Thanks in advance.

Upvotes: 0

Views: 131

Answers (2)

Alnitak
Alnitak

Reputation: 339826

The cleanest solution (IMHO) is a recursive callback loop - you just trigger the upload of the next piece of data when the previous AJAX call finishes.

$('button').click(function() {
    var a = array.slice(0);
    (function loop() {
        var text = a.shift();
        if (typeof text !== 'undefined') {
            $.post(url, {data: text})
             .done(function(data) {
                 // use result
                 ...
             }, loop);  // and iterate
        } 
    })();  // start the loop immediately
});

The code above takes advantage of the .done deferred object method and is passed two callbacks - one which is your traditional "success" callback, and the second which triggers the pseudo-recursive call back to the loop function.

Upvotes: 1

Grant Thomas
Grant Thomas

Reputation: 45083

If the data must arrive in order then you'll need to delay execution of further POSTs until the previous one has completed its rounds; you can do this in a number of ways, but the best bet would probably be a function that does the AJAX POST and accepts a parameter for the next item/index or whatever, and calls itself on the success callback of the AJAX call.

function submitData(items, index) {
  if (index < items.length) {
    $.post(
      "process.php",
      { data : items[index] },
      function(data) {
        submitData(items, ++index);
      }
    );
  }
}

Then call:

submitData(items, 0);

Upvotes: 1

Related Questions