0๐
โ
- Make sure you return a
response
asObject
(test usingconsole.log(typeof response)
) - Make sure to convert your data into the expected format (see the
dataToChartData
function that accepts an Array of objects). - Inside your success handler simply call this two lines:
myChart.data.datasets[0].data = dataToChartData(result);
myChart.update();
Example:
const config = {
type: 'line',
data: {
datasets: [{
label: 'This week',
data: [], // Set initially to empty data
borderColor: 'rgba(75, 192, 192, 1)',
backgroundColor: 'rgba(75, 192, 192, 0.2)',
}]
},
options: {
scales: {
xAxes: [{
// https://www.chartjs.org/docs/latest/axes/cartesian/time.html
type: "time",
distribution: "linear",
time: {
// parser: 'YYYY-MM-DD HH:mm:ss', // Not needed
unit: 'custom',
displayFormats: {
'custom': 'YYYY-MM-DD', // or like: 'YYYY-MM-DD HH:mm:ss',
}
},
ticks: {
source: 'data'
}
}],
yAxes: [{
ticks: {
beginAtZero: true,
}
}],
/*title: {
display: false
}*/
}
}
};
const ctx = document.querySelector("#vitalSignsCanvas").getContext("2d");
const myChart = new Chart(ctx, config);
const dataToChartData = arr => {
return arr.map(item => {
return {
x: item.SavedDate,
y: item.Answer
};
});
};
// Sample result for demo:
const result = [{
"Question": "Temperature", "QuestionID": 30060, "Answer": 87.00, "SavedDate": "2020-02-14T10:59:34.27Z", "PAHID": 1
},{
"Question": "Temperature", "QuestionID": 30060, "Answer": 92.00, "SavedDate": "2020-02-15T10:59:34.45Z", "PAHID": 2
},{
"Question": "Temperature", "QuestionID": 30060, "Answer": 64.00, "SavedDate": "2020-02-16T10:59:34.45Z", "PAHID": 3
},{
"Question": "Temperature", "QuestionID": 30060, "Answer": 67.00, "SavedDate": "2020-02-17T10:59:34.45Z", "PAHID": 4
},{
"Question": "Temperature", "QuestionID": 30060, "Answer": 98.00, "SavedDate": "2020-02-18T10:59:34.45Z", "PAHID": 5
},{
"Question": "Temperature", "QuestionID": 30060, "Answer": 77.00, "SavedDate": "2020-02-19T10:59:34.45Z", "PAHID": 6
},{
"Question": "Temperature", "QuestionID": 30060, "Answer": 81.00, "SavedDate": "2020-02-20T10:59:34.45Z", "PAHID": 7
}
];
// This goes inside the Success handler
myChart.data.datasets[0].data = dataToChartData(result);
myChart.update();
#vitalSignsCanvas {display: block; width: 100%; min-height: 200px;}
<h3>Vital Signs for: <span class="memberName">Chart</span></h3>
<canvas id="vitalSignsCanvas"></canvas>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chart.js@2.8.0"></script>
Code inspiration from my other answer (How to create a time series line graph in Chart js)
Source:stackexchange.com