Search code examples
javascriptdynamicchart.jsstacked-chart

how to insert dynamic data from sql into chartjs stacked bar chart javascript


I'm trying to create a dynamic stacked bar chart with chartJS. I know how to create the a regular bar chart but have a problem when I try to create the a stacked bar chart. For a stacked bar chart the data structure is different and I know how to constract it dynamically using javascript in the form

var inchartdatasets = [];
for (var i = 0; i < leninchart; i++) {
    var inlabel = 'label: ' + "'" + inchartlebals[i] + "'";
    var indata = 'data: ' + '[' + inchart[i] + ']';
    var indataset = '{' + inlabel + ',' + indata + ',backgroundColor: color,}'
    inchartdatasets.push(indataset)
}

The code above create the result in the following format (this is a copy from the alert) :

{label: 'AAA',data: [76.86],backgroundColor: color,},{label: 'Rating Unknown',data: [11.38],backgroundColor: color,},{label: 'BBB',data: [5.91],backgroundColor: color,},{label: '(1) others',data: [3.51],backgroundColor: color,}

To create the chart I use:

var data = {
    datasets :[
    {inchartdatasets}
    ],
};
var chart = new Chart ( ctx, {
    type : "horizontalBar",
    data : data,
    options : options,
});

this does not render the data on the chart even though the data in the alert is correct. when I copy the alert message and hard code in in the data in the following code:

var data = {
        datasets :[
        {label: 'AAA',data: [76.86],backgroundColor: color,},{label: 'Rating Unknown',data: [11.38],backgroundColor: color,},{label: 'BBB',data: [5.91],backgroundColor: color,},{label: '(1) others',data: [3.51],backgroundColor: color,}
        ],
    };

the chart render correctly.

what am I missing here? why it does not render dynamically? any help is appreciated. Thanks,


Solution

  • The issue is that what you are constructing is a String, but the data you need to pass to chart.js should be a JavaScript object. See, by taking e.g. the string '{' and concatenating it with other values, what you get is another string, which chart.js can't work with.

    Instead, what you need to do is construct your data as an object, something like this:

    var inchartdatasets = [];
    for (var i = 0; i < leninchart; i++) {
        var data = {
            label: inchartlebals[i],
            data: inchart[i],
            backgroundColor: color
        };
        inchartdatasets.push(data);
    }
    

    This MDN page might also be a helpful resource to get a better understanding of working with JavaScript objects.