6

I need a little help putting PHP data into google charts.

I have created a simple array

$chart_arr = array($year, $new_balance);
json_encode($chart_arr);    

If I run

<?php echo json_encode($chart_arr);?>    

I see the following: [2015,1150] [2016,1304.5] [2017,1463.635] [2018,1627.54405] [2019,1796.3703715], so I think (?) I am getting the right numbers encoded from my forloop that generates $year and $new_balance.

I want to chart these numbers in google chart

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

function drawChart() {


var data = new google.visualization.DataTable();
                data.addColumn('string', 'Year');
                data.addColumn('number', 'Balance');
                data.addRows([
                    <?php echo json_encode($chart_arr);?>
                ]);    

Or alternatively:

                data.addRows([
                <?php echo $chart_arr;?>
            ]);    

And then continues...

var options = {
              title: 'My Savings',
              curveType: 'function',
              legend: { position: 'bottom' } 
};

var chart = new google.visualization.LineChart(document.getElementById('curve_chart'));
chart.draw(data, options);

}

displaying as...

    <div class="grid-container"> 
    <div class="grid-100 grid-parent">
        <div id="curve_chart" style="width: 100%; height: auto"></div>
     </div>   

</div>

I have tried a number of variations but am either not getting the data into the chart or not getting a chart to display.

Could someone help me to show where I am going wrong?

I saw another related post that used the following code:

     $chartsdata[$i] = array($testTime, $testNb);
echo json_encode($chartsdata);

var jsonData = $.ajax({
        url: "test.php",
        dataType: "json",
        async: false
    }).responseText;

    var obj = JSON.stringify(jsonData);
    data.addRows(obj);

Is this the approach I need to be looking at?

Thanks in advance

0

3 Answers 3

7

i see you haven't found out how to do it after your first question, so i've made you a working example here, hope this helps you Dave :).

If you've got some questions about this, feel free to ask!

<?php 
//create array variable
$values = [];

//pushing some variables to the array so we can output something in this example.
array_push($values, array("year" => "2013", "newbalance" => "50"));
array_push($values, array("year" => "2014", "newbalance" => "90"));
array_push($values, array("year" => "2015", "newbalance" => "120"));

//counting the length of the array
$countArrayLength = count($values);

?>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);

function drawChart() {

    var data = new google.visualization.DataTable();
    data.addColumn('string', 'Year');
    data.addColumn('number', 'Balance');

    data.addRows([

    <?php
    for($i=0;$i<$countArrayLength;$i++){
        echo "['" . $values[$i]['year'] . "'," . $values[$i]['newbalance'] . "],";
    } 
    ?>
    ]);

    var options = {
        title: 'My Savings',
        curveType: 'function',
        legend: { position: 'bottom' } 
    };

    var chart = new google.visualization.LineChart(document.getElementById('curve_chart'));
    chart.draw(data, options);
}
</script>

<div class="grid-container"> 
<div class="grid-100 grid-parent">
    <div id="curve_chart" style="width: 100%; height: auto"></div>
</div>   

</div>
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks Koen. I couldn't get past the issue that all I charted was the ultimate value of $year and $newbalance for each year rather than the one corresponding to that year. I'll try this out. Thanks again.
Koen, Thanks again. Your code works fine. I guess the issue is that I don't understand enough so when trying to incorporate my $chart_arr data into it it fails and gives me no explanation why. I think I'll have to drop it as I've wasted too much time to achieve nothing. Thanks again for your help.
You can use foreach instead for
0

I have dealt quite a bit with the Google Charts API recently and I have a few recommendations. The PHP code that you have written should largely work, but it does require that your Javascript code be embedded in a PHP page.

Maybe that is okay for your purposes, but I mostly recommend keeping your Javascript separate from your PHP. Some developers may be comfortable with one, but not the other, so mixing the two languages could become a maintenance issue. Now, that pretty much leaves you with using AJAX to retrieve your JSON charts data. This is a good approach, but I do not like the code that you featured in your question for a few reasons.

Firstly, the code uses async: false which will remove your user's control of the browser while the data is being fetched. In other words, the browser will appear to freeze until the data is returned from the AJAX request.

Also, I do not understand the whole .responseText convention. I understand what the code is accomplishing; I just fail to understand why the author chose that particular approach. Here is what I would do instead.

$.ajax({
    url: "test.php",
    dataType: "JSON",
    data: [any POST parameters that you need here],
    type: "POST",
    success: function(json) {
        var jsonData = JSON.parse(json); // jsonData will be a Javascript object or array.
        data.addRows(jsonData);
        drawChart();
    },
    error: function(jxqhr) {
        // Handle a bad AJAX call
    }
});

So how does this help your application overall? Well, in your server side code, you can handle any errors (i.e. bad user input) by responding to the AJAX call with a HTTP 500 error and the AJAX call can communicate the problem to your user. Furthermore, when your page loads, the rest of the page will continue loading while your AJAX call is off fetching data.

JS Fiddle

9 Comments

Thanks Joel, I'm looking at these 2 suggestions. Could you clarify what should go with the data field? Secondly is this the correct way to represent the JSON data $chart_arr = array($year, $new_balance); json_encode($chart_arr); - thanks
The data option can be thought of as anything you might submit in an HTTP form. You can use JQuery's serialize method if you have a form with data on a page. As an example, suppose you allowed your user to select a date range for the data that will be graphed. The data field could be startDate=2015-01-01&endDate=2015-01-14. You could also create a Javascript object and use JSON.stringify. There are a lot of options available. If you really are seeing [2015,1150], [2016,1304.5], ... from your json_encode call then you do seem to be formatting your $chart_arr correctly.
the issue is that the $chart_arr data is not feeding into the google api. All I see is a chart with no data and a vertical scale from 0 to 1. What part of this function picks up the array data?
The success function in the AJAX call should pick up the data then add it to your Google DataTable. If you console.log(json) and console.log(jsonData) in the success function, what do you see?
Failed to load resource: net::ERR_CACHE_MISS
|
0

json_encode works just fine, you can put it in a variable like var grafica = <?php echo json_encode($grafica); ?> ; (look my example below) or just like you put it in your example, except that the only problem in it, is that you have double brackets, the ones inside jaso_encode($chart_arr) object and the externals data.addRows([ ... ]), that gives you [[...]] and generates and error, take off the brackets, try it like this:

 data.addRows(  
         <?php echo json_encode($chart_arr);?>  
           );

and not this

  data.addRows([  
     <?php echo json_encode($chart_arr);?>  
       ]);

I have included and example of how I am using it, be aware that in the documentation, (which in my opinion could be better) they placed the entire code in the <head> section because they have all the data there, but that may cause problems in real working examples, I only placed the CDN (Content Delivery Network) of google chart in the <head> and in the <body> all the Javascript code after the PHP code, not included in this example for clarity purposes, then the <div> but this last could go before the script tags. The order is important because you need to get the data first before constructing the graph.

I hope this helps.

<!DOCTYPE html>

    <head>

        <meta charset="utf-8"/>
        <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>

    </head>


<body>

<script type="text/javascript">

      google.charts.load("current", {packages:["corechart"]});       
      google.charts.setOnLoadCallback(drawChart);

      function drawChart() {

        var data = new google.visualization.DataTable();
       data.addColumn('string', 'fecha'); // Implicit domain column.
       data.addColumn('number', 'peso'); // Implicit data column.
       data.addColumn({type:'string', role:'annotation'}); // columna para anotaciones
       data.addColumn({type:'string', role:'style'});  // comumna para estilo


    var grafica =  <?php    echo json_encode($grafica);        ?> ;   

       data.addRows(grafica);


        var options = {
        title:'Peso Total', width:600,height:400,
        colors: ['#C0C0C0'],
        curveType: 'function',
          legend: 'none',
          pointSize: 12,
          annotations: {
                textStyle: {
                  fontName: 'Times-Roman',
                  fontSize: 32,
                  color: '#99ff99',
                  opacity: 0.5,
                }

              }

        };

        var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
        chart.draw(data, options);
      }
    </script>






 <div id="chart_div" style="margin: 80px auto; width: 650px; height: 450px; border: 2px solid #4CAF50; border-radius: 20px; padding:5px; "></div>


</html>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.