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;   
            }
        });
    }
}
2
  • 1
    possible duplicate of JavaScript variable binding and loop Commented Feb 12, 2014 at 20:51
  • 1
    You should read about closures in javascript and what elements cause variable capture and which ones don't. Commented Feb 12, 2014 at 20:54

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

1 Comment

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.
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);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.