Anna Jeanine Anna Jeanine - 1 month ago 21
jQuery Question

Highcharts with multiple series from JSON Dynamically

I am making a bar chart from HighCharts from JSON data which the user generates. The JSON is formatted like this:

[{"name":"project1","data":[50291,7410,2013,2013,524,201]},{"name":"project2","data":[1776995,758630,25633,4120054,24521,2045]}]


Because the user chooses the projects, this JSON data could also be of 5 projects! I need to be able to dynamically load in series into my highcharts. This is the code which I have now.

$(function () {

var options = {
chart: {
renderTo: 'container',
type: 'column',
options3d: {
enabled: true,
alpha: 0,
beta: 0,
depth: 0,
viewDistance: 25
}
},
title: {
text: 'Data'
},
subtitle: {
text: 'Dataset'
},
plotOptions: {
column: {
depth: 0
}
},
series: [],
xAxis: {
categories: ['XA', 'XB', 'XC', 'XD', 'XE', 'XF']
},

credits: {
enabled: false
}
};
$.getJSON('/uploads/test.json', function (list) {
var newseries = {
name: '',
data: []
};

$.each(list, function (i, item) {
newseries.name = item.name;
newseries.data = item.data;
options.series.push(newseries);
});
var chart = new Highcharts.Chart(options);


function showValues() {
$('#alpha-value').html(chart.options.chart.options3d.alpha);
$('#beta-value').html(chart.options.chart.options3d.beta);
$('#depth-value').html(chart.options.chart.options3d.depth);
}

// Activate the sliders
$('#sliders input').on('input change', function () {
chart.options.chart.options3d[this.id] = this.value;
showValues();
chart.redraw(false);
});

showValues();
});
});


This works when i only have one project in my chart, but when there are more the chart overwrites itself some way and only shows the last project in the JSON. Could someone please help me with this problem?

Answer

You are overwriting the name and data nodes of your newseries object each time you loop, by declaring them outside of the loop in that way.

I would turn this:

$.getJSON('/uploads/test.json', function (list) {
    var newseries = {
        name: '',
        data: []
    };

    $.each(list, function (i, item) {
        newseries.name = item.name;
        newseries.data = item.data;
        options.series.push(newseries);
    });
    var chart = new Highcharts.Chart(options);

Into something more like this:

$.getJSON('/uploads/test.json', function (list) {
    var newseries;

    $.each(list, function (i, item) {
        newseries = {};
        newseries.name = item.name;
        newseries.data = item.data;
        options.series.push(newseries);
    });
    var chart = new Highcharts.Chart(options);

Although really, in your case, you don't need to loop at all, because your return JSON is already in the proper format for Highcharts.

You can try something like

$.getJSON('/uploads/test.json', function (list) {
    options.series = list;
    var chart = new Highcharts.Chart(options);

Instead (untested, might need to be tweaked).