I'm using Donut Chart
And retrieve the data from database through PHP.
PHP
$q = oci_parse($c1, "SELECT DESCRIPTION, SUM(QUANTITY) AS TOTALS FROM TEST1
GROUP BY DESCRIPTION");
oci_execute($q);
while($d = oci_fetch_array($q))
{
$description[] = $d['DESCRIPTION'];
$quantity[] = $d['TOTALS'];
$nameAndCode = array();
$nameAndCode['label'] = $d['DESCRIPTION'];
$nameAndCode['y'] = $d['TOTALS'];
$namesArray[] = $nameAndCode;
}
$dataPoints = array(
"dataPoints" => $namesArray
);
echo json_encode($dataPoints);
And JS
var dataPoints = [];
function updateChart()
{
$.getJSON("data.php", function(result)
{
for (var i = 0; i <= result.dataPoints.length - 1; i++)
{
dataPoints.push({
label: result.dataPoints[i].label,
y: parseInt(result.dataPoints[i].y)
});
}
chart.render();
});
}
var chart = new CanvasJS.Chart("chartContainer", {
data: [{
type: "doughnut",
innerRadius: "40%",
showInLegend: true,
legendText: "{label}",
indexLabel: "{label}: #percent%",
dataPoints: dataPoints
}]
});
var updateInterval = 1000;
setInterval(function(){
updateChart()
}, updateInterval);
When I tried to run the code, the Donut Chart will always show so many duplicate. Data retrieve only 4 items.
My purpose is Donut Chart will always realtime to get data.
My question, how to prevent so many duplicate chart?
You should first empty the dataPoints array when you get the result and then you should iterate through it to populate.
Try something like;
$.getJSON("data.php", function(result)
{
$("#chartContainer").options.data[0].dataPoints = result;
$("#chartContainer").CanvasJSChart().render();
});
Example; https://jsfiddle.net/yumn325w/