Journeyman Journeyman - 11 days ago 5
Ajax Question

jQuery Ajax call in loop losing local variable reference

I am making several jQuery ajax calls within a loop. Each time one of the ajax calls return I need to reference a value corresponding to the original ajax call. My current code doesn't work properly, in that the value of the

lskey
variable has been altered by further loop iterations.

Here is the code:

for (var i = 0, len = localStorage.length; i < len; i++) {
var lskey = localStorage.key(i);
if (lskey.substr(0, 4) === 'form') {
var postdata = localStorage.getItem(lskey); // Get the form data
$.ajax({
type: "POST",
async: "false",
url: "/Profile/PostForm",
data: postdata,
success: function (data) {
$('#rollinginfo').append('<br>' + data + ',key=' + lskey);
localStorage.removeItem(lskey); // Remove the relevant localStorage entry
}
, error: function (data) { $('#rollinginfo').append('<br />ERR:' + data); }
});


}
}


The problem is that
lskey
is being altered each time the loop executes, and therefore the success callback does not have a reference to the value of lskey that existed at the time of the call.

How do I reference the correct value of
lskey
for each success callback?

Answer
for (var i = 0, len = localStorage.length; i < len; i++) {
    var lskey = localStorage.key(i);
    if (lskey.substr(0, 4) === 'form') {
        var postdata = localStorage.getItem(lskey); // Get the form data
        $.ajax({
            type: "POST",
            async: "false",
            url: "/Profile/PostForm",
            data: postdata,
            local_lskey: lskey
            success: function (data) {
                $('#rollinginfo').append('<br>' + data + ',key=' + lskey);
                localStorage.removeItem(this.local_lskey); // Remove the relevant localStorage entry
            }
        , error: function (data) { $('#rollinginfo').append('<br />ERR:' + data); }
        });
    }
}

This should work.