I am completely new to using chartjs in my laravel project. Currently, I am struggling to create a chart that updates automatically without refreshing the page, pulling data from a MySQL database. I came across this code online: https://codepen.io/jordanwillis/pen/bqaGRR. Despite trying to implement it, the output always seems to fail.
// Function used for illustration purposes
function getRandomIntInclusive(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min + 1)) + min;
}
// Creating an initial empty chart
var ctx_live = document.getElementById("mycanvas");
var myChart = new Chart(ctx_live, {
type: 'line',
data: {
labels: readingID,
datasets: [{
data: moist,
borderWidth: 1,
borderColor:'#00c0ef',
label: 'liveCount',
}]
},
options: {
responsive: true,
title: {
display: true,
text: "Chart.js - Dynamically Update Chart Via Ajax Requests",
},
legend: {
display: false
},
scales: {
yAxes: [{
ticks: {
beginAtZero: true,
}
}]
}
}
});
// The following code drives the example data
var readingID = [];
var moist = [];
// Logic to retrieve new data
var getData = function() {
$.ajax({
url: "/soildata",
type:"GET",
success: function(data) {
console.log(data);
data = JSON.parse(data);
// Process the retrieved data and update the chart accordingly
myChart.data.labels.push("ReadingID " + readingID++);
myChart.data.datasets[0].data.push(getRandomIntInclusive(1, 25));
// Re-render the chart
myChart.update();
}
});
};
// Retrieve new data every 3 seconds
setInterval(getData, 3000);
I believe some modifications need to be made in this function to ensure that the data from my database functions correctly: Chart.data.datasets[0].data.push(getRandomIntInclusive(1, 25));
Any suggestions or insights? As a beginner in chartjs, I have been struggling for weeks to solve this issue on my own. Any help, even if it involves providing different code snippets, would be highly appreciated. Thank you in advance for any assistance offered.