Hello everyone, I’m a beginner in JavaScript and I’m trying to edit this code that I found on CanvasJS forums:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title></title>
<script src="jquery.js"></script>
<script src="canvasjs.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$.getJSON("data.php", function (result) {
var chart = new CanvasJS.Chart("chartContainer", {
data: [
{
dataPoints: result
}
]
});
chart.render();
});
});
</script>
</head>
<body>
<div id="chartContainer" style="width: 800px; height: 380px;"></div>
</body>
</html>
It works correctly but I’d like to update my chart every second. I tried to write a function that updates chart every second using setInterval() but what I found impractical is that I have to recreate chart everytime, how’s it possible to only pass new data to existing chart in updateChart function without recreating chart every second, cause it looks inneficient to me.
This is what I tried:
$(document).ready(function() {
var updateChart = function() {
$.getJSON("chart.php", function (result) {
var chart = new CanvasJS.Chart("chartContainer", {
data: [
{
dataPoints: result
}
]
});
chart.render();
});
}
setInterval(function(){updateChart()},1000);
});
As you see chart is created every second, how should I update only dataPoints:result second time, because once chart is created there’s no point to recreate everything again.
Thank you in advance for the help you can provide me.
-
This topic was modified 9 years, 9 months ago by Elvinas. Reason: update
-
This topic was modified 9 years, 9 months ago by Elvinas.