1

I am trying to go through all over highchart serieses and at the same time perform ajax to the server. Let's see the code below

var url = './sheet';
for(var k = 0; k < chart.series.length; k++) {                      
    console.log(chart.series[k]);
    $.getJSON(url).done(function (data){
        if (data.length) {                              
            console.log(chart.series[k]);
        }
    });
}

I am not sure what is the problem with the code above. As you can see the reference to var k is lost when jQuery.getJSON is done. Appreciate if you can help me. Thank you

Muhaimin
  • 1,643
  • 2
  • 24
  • 48
  • 1
    `getJSON` is an async call, so the loop moves past the current index while your data call is in progress – tymeJV Jun 19 '14 at 14:56
  • 1
    See [How do javascript closures work?](http://stackoverflow.com/questions/111102/how-do-javascript-closures-work) – Jason P Jun 19 '14 at 14:57
  • Hrm.. I know this is a duplicate, but I can't decide on the best one... maybe [this one?](http://stackoverflow.com/questions/6077357/passing-index-from-for-loop-to-ajax-callback-function-javascript) – Jason P Jun 19 '14 at 15:04
  • after closure the ajax, i've been hit by **Uncaught RangeError: Maximum call stack size exceeded**. – Muhaimin Jun 19 '14 at 15:07
  • @MuhaiminAbdul What are you trying to do? That error usually means there's infinite/too much recursion somewhere. – Ben Fortune Jun 19 '14 at 15:20

1 Answers1

5

Your code is asynchronous, wrap it in a closure so it retains it's value in the loop.

var url = './sheet';
for(var k = 0; k < chart.series.length; k++) {                      
    (function(k){
        console.log(chart.series[k]);
        $.getJSON(url).done(function (data){
            if (data.length) {                              
                console.log(chart.series[k]);
            }
        });
    })(k);
}

As Jason referenced in the comments, learn how closures work.

Community
  • 1
  • 1
Ben Fortune
  • 31,623
  • 10
  • 79
  • 80