0๐
If you correctly sorted your data from your server and got a JSON response from, probably you can do something like this in your javascript (btw it is written in es6):
let myBalanceChart = document.getElementById("monthlyBalanceChart" + stock.id).getContext('2d');
let monthlyBalanceChart = new Chart(myBalanceChart, {
type: 'bar',
data: {
labels: monthlyBalancesMonths,
datasets: [{
label: "Monthly Balance",
data: monthlyBalances,
backgroundColor: [ // this is for design only
'rgba(255, 99, 132, 0.2)',
'rgba(54, 162, 235, 0.2)',
'rgba(255, 206, 86, 0.2)',
'rgba(75, 192, 192, 0.2)',
'rgba(153, 102, 255, 0.2)',
'rgba(255, 159, 64, 0.2)',
'rgba(255, 99, 132, 0.2)',
'rgba(54, 162, 235, 0.2)',
'rgba(255, 206, 86, 0.2)',
'rgba(75, 192, 192, 0.2)',
'rgba(153, 102, 255, 0.2)',
'rgba(255, 159, 64, 0.2)',
],
borderColor: [ // design
'rgba(255,99,132,1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(75, 192, 192, 1)',
'rgba(153, 102, 255, 1)',
'rgba(255, 159, 64, 1)',
'rgba(255,99,132,1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(75, 192, 192, 1)',
'rgba(153, 102, 255, 1)',
'rgba(255, 159, 64, 1)',
],
borderWidth: 1
}],
},
options: { // additional options for design/ tooltips
title: {
display: true,
text: 'Monthly Balances This Year',
fontSize: 25,
},
legend: {
position: 'right',
fontColor: '#000',
}
}
});
Where labels
in data
is a Javascript Array like:
["January", "February", "March"...]
and so on.
The data
from datasets
from data
is the array based on your monthly prices like:
[300, 1200, 900, ...]
and so on.
And make sure that the array length (or count) of labels
array must be the same in data
and properly ordered.
0๐
foreach($result as $res){
$month = $res->created_at->month();//will return month of the timestamp
$price = $res->price;
}
This is how you can retrieve month and price separately and pass it to chart.js in their specified format.
Note: try to understand the json format required by chart.js. Prepare your raw data in that json format and pass it to chart.js
For ex:
foreach($result as $res){
$data[$res->id]['month'] = $res->created_at->month;
$data[$res->id]['price'] = $res->price;
}
$data=json_encode($data);//this will encode the data array into json format.
Now you can pass this to chart.js and get your chart up. (I had done like this once. So this should work)
Also go through the chart.js google api for php to understand it better.