Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 738
Journeyman Avatar asked May 03 '11 14:05

Journeyman


2 Answers

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.

like image 144
Jack Avatar answered Nov 04 '22 18:11

Jack


In the end I added the key info to the server posting, and then returned it from the server in JSON format so the success function could then simply refer to the key contained in the server response.

like image 34
Journeyman Avatar answered Nov 04 '22 19:11

Journeyman