0

Say I have a loop and I want the value of the loop to be used in a ajax call, since the ajax call is async the calling delay of the ajax call will mean that only the last value of the loop variable (in the example=2) will be used not the counter value at the time the ajax function was called (0,1,2).

It seems that this can be achieved with bind or the jquery proxy function however all examples seem to use a normal function call example and I wanted to handle the data within the ajax call.

Here is an incorrect example that will always produce 2+val

function addVals()
{
    var i;
    for(i=0;i<3;i++)
    {
        $.get(url+"?"+params, function (val) {
            console.log(i+val);
        }
    }
}

This question is about binding in the case of ajax get/post requests rather than the binding mechanism of event handlers, anyway the following code works to solve the problem

for(var i=0;i<30;i++)
{
    $.getJSON(url).done($.proxy(function(json) { 
                     console.log(json);     // do stuff with your returned data
                     console.log(this.prop) // correct counter value here
                     }, {prop: i} ));
}

in this case outer will be the correct incremented value whereas inner is incorrect.

ejectamenta
  • 1,047
  • 17
  • 20

0 Answers0