-1

I am trying to show fetched data in Google charts, but PHP variables inside the javascript are not echoed.. If I echo variables outside of the javascript all works fine, so I suspect that something must be wrong in my javascript.. I double-checked everything but I can't figure our where is the issue..

The code does not show any errors!

This is the output in browser source..

['Active Posts',$post_counts],['Categories',$category_counts],['Users',$user_counts],['Comments',$comment_counts],

Any suggestion?

Thank you

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

        function drawChart() {
        var data = google.visualization.arrayToDataTable([
        ['Data', 'Count'],

            <?php 

            $data_text = ['Active Posts', 'Categories', 'Users', 'Comments'];
            $data_count = ['$post_counts', '$category_counts', '$user_counts', '$comment_counts'];

            for($i = 0; $i < 4; $i++) {

            echo "['$data_text[$i]'" . "," . "$data_count[$i]],";
            }

            ?>
          ]);

          var options = {
              chart: {
              title: '',
              subtitle: '',

              }
            };

            var chart = new google.charts.Bar(document.getElementById('columnchart_material'));

            chart.draw(data, google.charts.Bar.convertOptions(options));
            }

       </script>
Matt Domer
  • 29
  • 2
  • I know you solved your problem, but if you want to understand why this happens, here is a nice discussion about it. https://stackoverflow.com/questions/3446216/what-is-the-difference-between-single-quoted-and-double-quoted-strings-in-php – Badea Mihai Florin Oct 03 '17 at 06:28

2 Answers2

3

Since you're already using PHP to output data for JS, you can just use json_encode to convert your ARRAY to JSON data.

<?php
$data = [
    'Data'          => 'Count',
    'Active Posts'  => $post_counts,
    'Categories'    => $category_counts, 
    'Users'         => $user_counts, 
    'Comments'      => $comment_counts  
];

$json = json_encode($data);
?>


var data = google.visualization.arrayToDataTable("<?php echo $json; ?>");
parpar
  • 329
  • 1
  • 10
1

Remove quotes from php variables,

Use this,

$data_count = [$post_counts, $category_counts, $user_counts, $comment_counts];

instead of,

$data_count = ['$post_counts', '$category_counts', '$user_counts', '$comment_counts'];