0
for (var i = 0; i < 3; i++){
    $.ajax({
        url: "ajax.php",
        success: function(data){
            alert(i);
        }
    });
}

I need a solution to get alerts with "0", "1" and "2". Аt this time of course I see 3 alerts with "3".

Eddie
  • 1,436
  • 5
  • 24
  • 42
  • Try saving the value `i` into a temporary variable (e.g. `j`) inside the loop, and using that in the `success` handler. – millimoose Feb 24 '12 at 13:34
  • possible duplicate of [Variable in JavaScript callback functions always gets last value in loop?](http://stackoverflow.com/questions/2520587/variable-in-javascript-callback-functions-always-gets-last-value-in-loop) – Quentin Feb 24 '12 at 13:36
  • I tried - it didn't work – Eddie Feb 24 '12 at 13:36
  • @Inerdial — That will just create (and overwrite) a variable that is always a copy of i (or lagging very slightly behind it). – Quentin Feb 24 '12 at 13:37

3 Answers3

4

You need to put a closure around your $.ajax() call.

for (var i = 0; i < 3; i++){
    (function (loop_var) {
        $.ajax({
            url: "ajax.php",
            success: function(data){
                alert(loop_var);
            }
        });
    })(i);
}

Currently it is outputting 3 as my the time the Ajax returns the value of i is indeed 3.

jabclab
  • 14,786
  • 5
  • 54
  • 51
2

Use an anonymous function wrapper around the code to create a closure that will keep the value until the asynchronous response arrives:

for (var i = 0; i < 3; i++){

  (function(i){

    $.ajax({
      url: "ajax.php",
      success: function(data){
        alert(i);
      }
    });

  })(i);

}
Guffa
  • 687,336
  • 108
  • 737
  • 1,005
0

Pass the i value to the ajax.php page as a parameter. The ajax.php page has to return i to the calling page. So let the ajax.php page return i. You can use json objects or a trivial pipe-separated string to store returning values from ajax.php.

for (var i = 0; i < 3; i++){
    $.ajax({
        data: {par: i},
        url: "ajax.php",
        success: function(data){
            //data is a pipe-separated string
            var cnt = data.split("|")[0];
            alert(cnt);
        }
    });
}
Alberto De Caro
  • 5,147
  • 9
  • 47
  • 73