Hello good I am making a graph where it is going to show the temperature during the time, what I need is to do it in real time, I found chart.js but I do not know how to add data from the database to the graph.
var ctx = document.getElementById("lineChart2").getContext("2d");
const labels = {{ time | safe }};
const values = {{ temp | safe }};
var lineChart = new Chart(ctx, {
type: "line",
data: {
labels: labels,
datasets: [
{
label: "Temperatura °C",
data: [values],
fill: false,
borderColor: "#28a745",
lineTension: 0.1
}
]
},
options: {
scales: {
x: {
type: 'realtime',
realtime: {
onRefresh: chart => {
chart.data.datasets.forEach(dataset => {
dataset.data.push({
x: //IT'S HERE labels
y: //IT'S HERE values
});
});
}
}
}
},
}
});
const labels = [1637903351687, 1637903353675, 1637903355678, 1637903357678, 1637903359674, 1637903361679, 1637903363672, 1637903365668, 1637903367686, 1637903369669, 163790337167] //time unix
const values = [24, 24, 5, 10, 1, 30, 1] //temperature
According to the Chart.js documentation you can update your graph with something like this:
async function updateGraphWithData() {
const data = await apiCall(); // Your call to your backend
lineChart.data.datasets.forEach(dataset => {
dataset.data = data;
});
lineChart.update();
}
You need something which will trigger the function (like a button click) or something else.