[Chartjs]-Can't pass data to chart.js graph

1👍

You are doing most everything right, but you are changing ‘type’ of the data…..

what you are doing RIGHT

var defaultDataW = [];

This sets the data to an ARRAY.

Though, in the ajax, you are doing this:

defaultDataW = data.weight;

Which, by your other comments, clearly says that ‘data.weight’ is an INTEGER.

So, when you try to use that (now INTEGER) as data in a Chart

data: defaultDataW,

It doesn’t work (and, no surprise……)

Chart.js requires an ARRAY (at minimum) to work – https://www.chartjs.org/docs/master/general/data-structures/

Now, how can you fix this?????

Pretty simple……

In your ajax, change

defaultDataW = data.weight;

To ADD to the ARRAY (instead of replacing the array with an integer….)

defaultDataW.push(data.weight);

In case you add other code later (or for future projects, putting things in a function, etc….), you might want to also learn about a way to CLEAR that array. It doesn’t hurt to do it now, though the way your code is it really should not be needed. I’m including it here for others to reference, etc.

Before doing a ‘push’ (certainly if you are doing a loop, etc.), you may need to clear the array first, like this:

defaultDataW.length = 0;

This will empty the array and then you can ‘push’ what you really want in there. If the array is not empty and you push, then you will have the old data as well as the new (of course, depending on what you are doing, that may be a good thing – though in this case, it is not)

Leave a comment