Search code examples
javascriptphpgoogle-visualization

Google charts problem with values on charts


Hey all can anyone help me with the problem i have with google charts.

The problem is numbers are not scaled 1, 2, 3, ... you can see on image on left side of chart. enter image description here

JavaScript and PHP code

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

    function drawChart() {
      var data = google.visualization.arrayToDataTable([
        ['Data', 'Count' , 'Approved' , 'Drafted'],
        <?php
      $elements_text = ['Posts' , 'Categories', 'Users','Comments'];
      $element_count =[$post_count,$categories_count,$users_count,$comment_count];
      $element_published = [$published_posts,'0',$admins_count,$approved_comments_count];
      $element_drafted = [$drafted_posts,'0',$subscriber_count,$unapproved_comments_count];


      for($i =0; $i<4 ; $i++){
        echo "['{$elements_text[$i]}'" . "," . "'{$element_count[$i]}'" . "," . "'{$element_count[$i]}'" . "," . "'{$element_drafted[$i]}'],";
      }
         ?>


      ]);

      var options = {
        chart: {
          title: 'Admin data',
          subtitle: 'Charst panel',
        }
      };

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

      chart.draw(data, google.charts.Bar.convertOptions(options));
    }
</script>

You can see that 6 is less than 0 :D


Solution

  • Crucially, this is not how to pass data from PHP to JavaScript. Never under any circumstances try to build your own JSON or other such structures; it will never work consistently. Use json_encode() for this. In addition to properly escaping strings, it also ensures that integers are properly passed as such.

    <?php
    $elements = [
        ["Data", "Count", "Approved", "Drafted"],
        ["Posts", $post_count, $published_posts, $drafted_posts],
        ["Categories", $categories_count, 0, 0],
        ["Users", $users_count, $admins_count, $subscriber_count],
        ["Comments", $comment_count, $approved_comments_count, $unapproved_comments_count],
    ];
    ?>
    <script>
    google.charts.load("current", {packages: ["bar"]});
    google.charts.setOnLoadCallback(drawChart);
    function drawChart() {
        const elements = <?= json_encode($elements) ?>;
        const data = google.visualization.arrayToDataTable(elements);
        const options = {chart: {title: "Admin data", subtitle: "Chart data"}};
        const chart = new google.charts.Bar(document.getElementById("columnchart_material"));
        chart.draw(data, google.charts.Bar.convertOptions(options));
    }
    </script>
    

    If you continue to have problems after fixing this code, I suggest you take a look at the data you're passing to the chart as it's likely not what you expect. Since your original code was repeating data from $element_count[$i] that's probably your problem.