0

On condition calling Ajax, but it is returning last value.

Here is my code

if(f_ref==209){
        array1=[1,2,3,4,5,6];
        for(var i = 0; i < array1.length; i++) {
            console.log("loop", array1[i], i, array1.length);
            getvalue = array1[i];
            $.ajax({
                headers: {
                    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                },
                type: "POST",
                dataType: 'json',
                url: "/getReportData",
                data: { getvalue:getvalue},
                //cache: false,
                success: function(result) {
                    console.log(result.length);
                    resultarr=result;
                    console.log(resultarr.length);
                    console.log(i);
                    if(i==0){
                        $("#1").val(resultarr.length);
                        console.log(resultarr.length);
                    }
                    else if(i==1){$("#2").val(resultarr.length);}
                    else if(i==2){$("#3").val(resultarr.length);}
                    else if(i==3){$("#4").val(resultarr.length);}
                    else if(i==4){$("#5").val(resultarr.length);}
                    else if(i==5){$("#6").val(resultarr.length);}                      
                },
                error: function(error) {
            
                    console.log(error);
                }
            });            
          }
    }

On if condition true it goes inside, Assign array1 values. For condition is true, goes inside.

console.log("loop", array1[i], i, array1.length) Value here is 1, 1, 0, 6

Condition is true it should go inside Ajax and call data on success. But it is returning zero value.

On checking here "console.log(i)" It is giving output 6 for each loop.

Why is this happening, i have no clue.

whats wrong in code above. Why for 'i'=6 it is taking Ajax request, also for 'i' = 6 condition is false why it is gong inside

Aram
  • 1
  • 3

1 Answers1

0

I changed a few details in your snippet to make it run here in SO. The problem you are encountering is caused by the fact that by the time your success function steps into action the for loop has long finished, leaving you with an i and a getvalue corresponding to that state. In my snippet I created a scope in form of an "immediately invoced functional expression" (IIFE) to preserve the getvalue so I can use it in the ensuing call of the success function:

const f_ref = 209;
if (f_ref == 209) {
  array1 = [1, 2, 3, 4, 5, 6];
  for (var i = 0; i < array1.length; i++) {
    // console.log("loop", array1[i], i, array1.length);
    (getvalue => $.ajax({ // ==> IIFE, creating a scope for getvalue
      // headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},type: "POST",  
      dataType: 'json',
      // url: "/getReportData",
      url: "https://jsonplaceholder.typicode.com/users/" + getvalue, // mock API
      // data: {getvalue: getvalue},
      //cache: false,
      success: function(result) {
        $("#i" + getvalue).val(`i:${i} getvalue:${getvalue} - ${result.name}`);
      },
      error: function(error) {
        console.log(error);
      }
    }))(array1[i]); // ( end of IIFE )
  }
}
input {
  width: 300px
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h3>Users</h3>
<input type="text" id="i1"></input><br>
<input type="text" id="i2"></input><br>
<input type="text" id="i3"></input><br>
<input type="text" id="i4"></input><br>
<input type="text" id="i5"></input><br>
<input type="text" id="i6"></input>

In my snippet I inserted both, the current (unpreserved) i and the preserved getvalue, into each input field to demonstrate that the value of i is always 6 - as expected, after the loop has finished.

Carsten Massmann
  • 26,510
  • 2
  • 22
  • 43