Working Around Closure in JQuery “ajax” Method

I’m relatively new to javascript and although I know what’s causing the bug, I’m not sure how to refactor this to make it work.

for ( ... ) {
    var variableQueryValue = i

    addLink.bind('click', function() {
        $  .ajax({
            type: 'POST',
            url: '/example',
            data: 'queryvalue=' + variableQueryValue,
            success: function(data) {
                console.log('Got into success method!');
            }
        });
    });
}

So basically we are binding a click event to some element whose data attribute is dependent on some variableQueryValue that changes every iteration. Because of the closure of the bind function handler, in the ajax request it will bind an event handler that uses the same value of variableQueryValue for each iteration.

How can I refactor this such that the updated variableQueryValue is taken into account?

Thanks for any help!

newest questions tagged jquery – Stack Overflow

About Admin