Use php variable in google pie chart

I want to use my PHP variable in a Google chart, but the chart cannot read my PHP tag. Since you can see the code below, I put my PHP variable in a script. (The PHP variable that I defined at the top of the code, and the result is correct). What happened to my code? Is there a solution for this? If necessary, check with me for more information. Thank.

<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>
+4
source share
3 answers

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>
+2
source

docs, Google string number.

, Amount integer float. php javascript, ,

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

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

javascript parseFloat() parseInt(), .

+2

You can use scripts in PHP.

But you cannot use PHP in scripts.

This will not work.

-1
source

Source: https://habr.com/ru/post/1661777/


All Articles