I have the following JQuery:
$(document).ready(function() {
var names = ['item1', 'item2'];
var series1 = [{ name: '', data: []}];
var series2 = [{ name: '', data: []}];
var seriesCounter = 0;
....
renderCharts(url, otherUrl);
function renderCharts(url, otherUrl) {
if (otherUrl != '') {
$.each(names, function (i, name) {
$.getJSON('somurl', function (items) {
series1[i].name = name;
$.each(items.somedata, function (j, item) {
series1[i].data.push({
x: Date.parse(item.key),
y: item.value
})
});
seriesCounter++;
if (seriesCounter == names.length) {
... render chart once all data has been downloaded
}
});
});
}
$.getJSON(url, function (items) {
$.each(items.otherData, function (i, item) {
series2[0].data.push({
x: Date.parse(item.Key),
y: item.Value
})
});
// render other chart
});
}
}
I can’t get this to work. Every time I run this I never enter the following condition:
if (seriesCounter == names.length) {
... render chart once all data has been downloaded
}
If I only have one item in the names array, it works just fine. The moment I add two, the condition never becomes true and therefore my charts never renders.
What am I missing?
Your
series1variable is defined as an array with exactly one element (an object) in it, but within the$.each(names, function (i, name) {loop you are treating it as if it had more elements and trying to accessseries1[i]for values ofithat are greater than 0. Wheniis 1 you are trying to doseries1[1].namebutseries1[1]is undefined and has nonameproperty.Your script would be stopping at that point, so the line
if (seriesCounter == names.length) {isn’t reached.I suggest you declare
series1as an empty array and then within the loop add a new item as needed:(You don’t have the same problem with
series2because although you’ve declared it as an array too you only ever access array element 0.)