Chartjs-Php Array to line chart in ChartJs

0👍

keep your array as it is and convert it to JSON object and then echo it inside Javascript, javascript have to be inside php file to run, not in external javascript file.

notice that there is PHP code in this example and i have put <?php echo $json; ?> inside the javascript code.

<html>
    <head>
        <style>body{width: 800px;}</style>
        <script src="https://cdn.jsdelivr.net/npm/chart.js@2.8.0"></script>
    </head>
    <body>
        <div>
            <canvas  id="myChart" width="700px" height="300px"></canvas>
        </div>      
        <?php
            $array = array(600, 800, 1200, 1800);
            $json = json_encode($array);
        ?>
        <script>
            var ctx = document.getElementById('myChart').getContext('2d');
            var chart = new Chart(ctx, {
              // The type of chart we want to create
              type: 'line',

              // The data for our dataset
              data: {
                labels: ["20", "40", "60", "80"],
                datasets: [
                  {
                    label: 'Monday',
                    borderColor: "#FF9F40",
                    data: <?php echo $json; ?>,
                  },
                  {
                    label: 'Tuesday',
                    borderColor: "#FF6384",
                    data: [600, 800, 1200, 1800]
                  },
                  {
                    label: 'Wednesday',
                    borderColor: "#219151",
                    data: [600, 800, 1200, 1800]
                  }
                ]
              },

              // Configuration options go here
              options: {}
            });
        </script>
    </body>
</html>

Leave a comment