Search code examples
jqueryajax-request

Jquery/Javascript - Variables scope and behaviour in jquery ajax requests


I'm with an weird behaviour that I cannot understand. Here is the code:

$.ajax({
    url: ...,
    dataType: ...,
       data: ...,
    success: function( data ) {
            ...

            for (var i=0; i<data.length; i++) {

                label_to_change = "some-" + i + "-item"

                        $.ajax({
                            url: ...,
                            dataType: ...,
                               data: ...,
                            success: function( data ) {

                                // Why I can't access the value in each loop, this will give me allways the last loop value
                                console.log(label_to_change)
                            }
                        }); 
            } 
    }
}); 

I need to access the var label_to_change in the second ajax request but instead of getting this:

some-0-item
some-1-item
some-2-item

I got this:

some-2-item
some-2-item
some-2-item

Any clues on what I'm doing wrong?

Best Regards,


Solution

  • The problem is because the label_to_change variable is a single instance, and the for loop is changing it 3 times before any of your ajax calls can complete. You could use an anonymous function (or whatever the correct term here is) and do something like this:

    label_to_change = "some-" + i + "-item";
    
    (function(newLabel){
        $.ajax({
           url: ...,
           dataType: ...,
           data: ...,
           success: function( data ) {
              console.log(newLabel)
           }
        }); 
    })(label_to_change);