Skip to content
Advertisement

Live updating chart with data from database with Chart.js

I’ve been having some trouble with Chart.js. I’m making a voting system that I want to dynamically update for the user to see. Kind of like strawpoll websites. When the user submits a vote, the results page will automatically update to the new vote count. I’ve been searching for an answer to this, and I feel like I’ve gotten halfway. I can get the actual chart to update, but it just duplicates the data and keeps on going forever. I want it to “replace” or just update the number and/or see for new voting questions as well.

Pic of the chart duplicating every second The chart duplicating.

Here’s the code I’m running:

<div id="chart-container">
    <canvas id="dataChart"></canvas>
</div>
<script>
    var ctx = $("#dataChart");
    var dataChart = new Chart(ctx, {
        type: 'bar',
        data: {
            labels: [],
            datasets: [{
                label: '<?php echo($row['vote_name']) ?>',
                backgroundColor: '#49e2ff',
                borderColor: '#46d5f1',
                hoverBackgroundColor: '#CCCCCC',
                hoverBorderColor: '#666666',
                data: [],
            }]
        },
        options: {}
    });

    var updateChart = function() {
        $('#dataChart').html('');
        $('#dataChart').html('<canvas id="dataChart"></canvas>');
        $.ajax({
            url: "data.php?form=<?php echo($vote_id) ?>",
            type: "GET",
            dataType: "json",
            success: function(data) {
                console.log(data);
                var name = [];
                var marks = [];
                for (var i in data) {
                    dataChart.data.labels.push(data[i].question);
                    dataChart.data.datasets[0].data.push(data[i].vote_count);
                }
                dataChart.update();
            },
            error: function(data) {
                console.log(data);
            }
        });
    }

    updateChart();
    setInterval(() => {
        updateChart();
    }, 1000);
</script>

Question is: Is there a reason that this isn’t working? I can’t seem to get it right, no matter what I try. Any help would be appreciated!

Advertisement

Answer

Following the suggestion, Tushar made in his comment, the success function could be changed as follows:

success: function(data) {
  dataChart.data.labels = data.map(v => v.question);
  dataChart.data.datasets[0].data = data.map(v => v.vote_count);
  dataChart.update();
},

This solution uses the Array.map() method that creates a new array populated with the results of calling the provided function on every element in the array.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement