Chartjs-How to use php variables in a chart js chart

1👍

Use php Join function

// 1. fictional array defined in PHP
<?php 
    $arr=[15, 19, 3, 17];
    ?>
<script>
var ctx = document.getElementById('myChart').getContext('2d');

// 2. convert the php array into a javascript variable
var dataArray = [<?php echo join(',',$arr); ?>];
var myChart = new Chart(ctx, {
    type: 'line',
    data: {
        labels: ['Excellent', 'Good', 'Fair', 'Poor'],
        datasets: [{
            label: 'This Month',
            data: dataArray, // 3. use the javascript variable here.
            backgroundColor: "rgba(153,255,51,0.4)"
        }, {
            label: 'oranges',
            data: [2, 29, 5, 5, 2, 3, 10],
            backgroundColor: "rgba(255,153,0,0.4)"
        }]
    }
});
</script>

Leave a comment