javascriptphpgoogle-pie-chart

Use php variable in google pie chart


I want to use my PHP variable in Google chart,but the chart couldn't read my PHP tag. As you can see the code below I put my PHP variable in the script. (The PHP variable I have defined at top of the code and the result is correct). What's wrong with my code ? Is there any solution for this ? Do ask me for more information if needed. Thank you.

<script type="text/javascript">
  google.charts.load('current', {'packages':['corechart']});
  google.charts.setOnLoadCallback(drawChart);
  function drawChart() {

    var data = google.visualization.arrayToDataTable([
      ['Order', 'Amount'],
      ['Completed',     '<?php echo$completed ?>'],
      ['New',      '<?php echo$new ?>']
    ]); 

    var options = {
      title: 'Total Order ' + <?php echo$total; ?>
    };

    var chart = new google.visualization.PieChart(document.getElementById('piechart'));

    chart.draw(data, options);
  }
</script>

Solution

  • Working Example.

    <?php 
    $completed = 50;
    $new = 10;
    $total = 30;
    ?>
    <html>
        <head>
            <!--Load the AJAX API-->
            <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
            <script type="text/javascript">
    
    
                google.charts.load('current', {'packages':['corechart']});
                google.charts.setOnLoadCallback(drawChart);
                function drawChart() {
    
                    var data = google.visualization.arrayToDataTable([
                        ['Order', 'Amount'],
                            ['Completed', parseInt('<?php echo $completed; ?>')],
                            ['New',       parseInt('<?php echo $new; ?>')]
                    ]); 
    
                    var options = {
                        title: 'Total Order ' + <?php echo$total; ?>
                    };
    
                        var chart = new google.visualization.PieChart(document.getElementById('piechart'));
    
                        chart.draw(data, options);
                    }
    
            </script>
        </head>
    
        <body>
            <div id="piechart"></div>
        </body>
    </html>