Adding data to a Chart after the page is loaded using php and chart.js

Viewed 76

Problem: Well I´m trying to generate a chart using chart.js with information retrieved from a query. The controller retrieves the data and then I use the data in the function responsible for inserting new data in the chart addData. But this function is only called after the page is loaded, because the function addData is only available after the page is loaded. The main problem is that, the labels appear correct but data doesn´t appear in the chart.

When I use console.log on the chart.data and It shows the correct data that I´m trying to insert:

Objectdatasets: Array(1)0: {label: "Eventos", lineTension: 0.3, backgroundColor: "rgba(78, 115, 223, 0.05)", borderColor: "rgba(78, 115, 223, 1)", pointRadius: 3, …}data: (12) ["26", "26", "34", "22", "36", "39", "20", "6", "11", "13", "18", "250"]0: "26"1: "26"2: "34"3: "22"4: "36"5: "39"6: "20"7: "6"8: "11"9: "13"10: "18"11: "250"length: 12__proto__: Array(0)label: "Eventos"length: 1__proto__: Array(0)labels: (12) ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]0: "Jan"1: "Feb"2: "Mar"3: "Apr"4: "May"5: "Jun"6: "Jul"7: "Aug"8: "Sep"9: "Oct"10: "Nov"11: "Dec"length: 12__proto__: Array(0)__proto__: Object

The controller that returns the information for the chart.

<?php
    function chart_area_eventos(){
            
            foreach(parent::get_chart_area_eventos() as $data){
    
                $values[] = $data->{'counter'};
                $labels[] = $data->{'month_name'};
            }
            $labels = json_encode($labels);
            $values = json_encode($values);
            ?>
        <script>
        window.addEventListener('load',function() {
        
            addData(myLineChart, <?php echo $labels.','.$values;?> , 'Eventos');
        });
        </script>
<?php } ?>

Where the chart is generated.

<div class="chart-area">
  <canvas id="myAreaChart"></canvas>
    <?php echo eventosController::chart_area_eventos();
</div>

JS Function responsible for adding the new values and new labels.

<script>
        function addData(chart, labels, data, label) {
            chart.data.labels = labels;
            chart.data.datasets.label = label;
            chart.data.datasets[0].label = label;
            chart.data.datasets.data = data;
        chart.update();
        chart.render();
        }
</script>
0 Answers
Related