-1

I am calling ajax function inside for loop. But I am getting 1 inside ajax success. fiddle

function a(){
var myAr= [0];
    for(var i=0; i<myAr.length;i++){
                console.log(i +" a")
    var root = 'http://jsonplaceholder.typicode.com';
        $.ajax({
          url: root + '/users',
          method: 'GET'
        }).then(function(data) {

        console.log(i + " c")

        });

                console.log(i + " b")
    }

}

a()
Jitender
  • 7,593
  • 30
  • 104
  • 210

3 Answers3

1

The .then() gets executed only when the response of the AJAX is received.

At that point, i is 1 because the foor loop is over.

If you want the original value when the AJAX request was created, you could create a new variable on the local scope with the value in i. That way, the closure executed inside the .then() method has the original value.

Updated fiddle.

Matheus208
  • 1,289
  • 2
  • 13
  • 26
1

U have to use closure for this, otherwise it evaluate to last value of i executed

 function a(){
var myAr= [0];
  for(var i=0; i<myAr.length;i++){
            console.log(i +" a")
    var root = 'http://jsonplaceholder.typicode.com';
    $.ajax({
      url: root + '/users',
      method: 'GET'
    }).then(function(i) {return function(data) {
    console.log(i + " c")

    }}(i));

            console.log(i + " b")
}

}

a()
0

As per your code console.log(i + " c") only executed when ajax call is done. For this kind of functionality you have to trigger it in a different way.

Here is a working demo.

function a() {
   var myAr= [0, 2, 3];
   var startIndex = 0;

   var doAjaxCall = function(i) {
       console.log(i +" a");
       var root = 'http://jsonplaceholder.typicode.com';
        $.ajax({
          url: root + '/users',
          method: 'GET'
        }).then(function(data) {
            console.log(i + " c");
            if(i < (myAr.length - 1)) {
                i++;
                doAjaxCall(i);
            }
        });
   }

   doAjaxCall(startIndex);
}
a();
Deepak Biswal
  • 4,280
  • 2
  • 20
  • 37