简体   繁体   中英

jQuery canvasjs donut chart realtime retrieve data

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/

Delete and ReCreate Chart Container (CANVAS) every time

    function updateChart()
    {
       document.getElementById("divDonutChart").innerHTML = '&nbsp;';
       document.getElementById("divDonutChart").innerHTML = '<canvas 
       id="chartContainer"> </canvas>  ';

        $.getJSON("data.php", function(result)
        {

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM