2

I need to access the i variable from the loop, in the success function. How do I do that?, can I pass it in to the function?

function save(){
    var mods=model.things;
    for (i in mods) {
        var mod= mods[i];
        $.ajax({
            url: "duck"
            type: "put",
            data: JSON.stringify(mod),
            success: function(responce_json) {
                var j=i;   
            }
        });
    }
}
ctrl-alt-delor
  • 7,506
  • 5
  • 40
  • 52
  • 1
    possible duplicate of [JavaScript variable binding and loop](http://stackoverflow.com/questions/1676362/javascript-variable-binding-and-loop) – DrLivingston Feb 12 '14 at 20:51
  • 1
    You should read about closures in javascript and what elements cause variable capture and which ones don't. – DrLivingston Feb 12 '14 at 20:54

2 Answers2

3

One way:

        success: (function(i) { return function(responce_json) {
            var j=i;   
        }})(i)

This uses an Immediately Invoked Function Expression (IIFE) to create a closure that will capture the current value of i.

Incidently, for...in is considered bad practice by a lot of JavaScript programmers, but if you need to use it, you should probably at least include a check for hasOwnProperty

Matt Burland
  • 44,552
  • 18
  • 99
  • 171
  • I went for a different answer because I could read the code. However +1 for the comment on `for…in`, can you tell me the alternative. – ctrl-alt-delor Feb 12 '14 at 21:11
1

Create another function that takes i as a parameter thus creating a local copy for each iteration

var f = function(i) { 
    var mod= mods[i];
    $.ajax({
        url: "duck"
        type: "put",
        data: JSON.stringify(mod),
        success: function(responce_json) {
            var j=i;   
        }
    });
}
for (iter in mods) {
    f(iter);
}
JaredPar
  • 733,204
  • 149
  • 1,241
  • 1,454