0

So I'm using Canvas.js to build a chart, and I want datapoints in this chart to be taken from the Json response I get earlier in my script. At the moment my code looks as follows:

$.post('admin/weekly_websites/json', data, function(response){
    points = $.parseJSON(response);
    console.log(response);
});
var chart_websites_week = new CanvasJS.Chart("chartContainerWebsitesWeekly", {
    animationEnabled: true,
    height: 300,
    width: 600,
    title: {
        text: 'Websites'
    },
    data: [              
        {
            type: "line",
            dataPoints: points
        }
    ]
});
chart_websites_week.render();

And it does not seem to work. It is said in CanvasJs documentation that datapoints could be taken from variable, but this variable should be an array like:

dataPoints: [
    {label: 'tomato', y: 8},
    {...}
]

My Json response lloks as follows:

[{"label":"2016-04-03","y":58},{"label":"2016-04-06","y":43}]

And when I try to parse it, I get an array of objects, and nothing gets shown on my chart. But if I copy this string from console log and just put it in dataPoints, everything works fine. How could I parse Json NOT in object array, or what could be an other solution to my problem? Would highly appreciate any possible help!

Coffee
  • 2,063
  • 8
  • 24
  • 57
  • Are you sure that you try to render AFTER you have received the JSON? From your code it is not clear, if render() is called after post() has finished. – Nils May 03 '16 at 13:09
  • yep, that was the problem, I added timeout to chart rendering and everything is workink great. thank you @Nils – Coffee May 03 '16 at 13:25
  • You should use the success() function of post() instead of timeout, but for testing timeout is sufficient... maybe read into js promises. – Nils May 03 '16 at 13:29

0 Answers0