I'm using an XMLHTTPRequest to receive data from a PHP file. The PHP file will echo at a number, say 6, and the XMLHTTPRequest will grab it. This is an attempt to make the graph live.
The problem I'm having relates to ChartJS and these requests.
var Data;
function loadXMLDOC() {
var request = new XMLHttpRequest(); // create http request
request.onreadystatechange = function() {
if (request.readyState == 4 && request.status == 200) {
Data = this.responseText;
myChart.data.labels.push(" ");
myChart.data.datasets[0].data.push(Data);
// re-render the chart
myChart.update();
}
}
request.open('GET', "data.php", true);
request.send(); // send the request
}
setInterval(function(){
loadXMLDOC();
}, 1000)
window.onload = loadXMLDoc;
As I'm grabbing these numbers from a database, I only need the number once. However, it will repeat the number multiple times, not once. Numbers Repeating on ChartJS I was wondering how I would only get the number once and have it not repeat multiple times till the next number comes in?
As Manuel suggested you can check if the latest number added is the same number as you want to add. If this is the case dont add it. Side effect from this is, if the next number is actually the same number as the last one it also wont be added. To achieve this you can change your function to this:
if (request.readyState == 4 && request.status == 200) {
Data = this.responseText;
const chartData = myChart.data.datasets[0].data;
if (chartData[chartData.length - 1] === Data) {
return;
}
myChart.data.labels.push(" ");
myChart.data.datasets[0].data.push(Data);
// re-render the chart
myChart.update();
}
Another option is to let PhP not send the number if it already has been sent.