Home » Php » Passing PHP array into Javascript through JSON to update Google Chart

Passing PHP array into Javascript through JSON to update Google Chart

Posted by: admin July 12, 2020 Leave a comment

Questions:

I have three PHP arrays that I’ve encoded with json… extra PHP code has been omitted because the arrays work properly…. Additionally, the HTML tags that call the google chart have been omitted for sake of brevity…

<?php
$encoded_line_volume = json_encode($LineVol) . "\n";
$encoded_loan_volume = json_encode($LoanVol) . "\n";
$encoded_cluster_name = json_encode($ClusterLine) . "\n";
?>

I would like to access these three arrays in Javascript to update my Google Chart dynamically.

<script type="text/javascript">

google.load("visualization", "1", {packages:["columnchart"]});
google.setOnLoadCallback(drawChart);

var linevol = new Array;  // This would be the first array passed from PHP
var loanvol = new Array;  // This would be the second array passed from PHP
var clusters = new Array; // This would be the third array passed from PHP

function drawChart() {
    var data = new google.visualization.DataTable();

    data.addColumn('string', 'Cluster');
    data.addColumn('number', 'Loans');
    data.addColumn('number', 'Lines');

/* create for loops to add as many columns as necessary */

var len = jsonarray.length;

    data.addRows(len);

for(i=0; i<len; i++) {

data.setValue(i, 0, ' '+clusters[i]+'');     /* x-axis */
data.setValue(i, 1, linevol[i]);   /* Y-axis category #1*/
data.setValue(i, 2, loanvol[i]);   /* Y-axis category #2*/
}
/*********************************end of loops***************************************/
  var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
  chart.draw(data, {width: 400, height: 240, is3D: true, title: 'Prospect Population', legend: 'right'});
}
</script>
How to&Answers:

You probably want them to become Javascript variables. When your php executes, it creates code your web browser then interprets. So you want to define javascript strings using php. For example:

<script type="text/javascript">
    var encoded_line_volume = <?php echo json_encode($LineVol) ?>;
    var encoded_loan_volume = <?php echo json_encode($LoanVol) ?>;
    var encoded_cluster_name = <?php echo json_encode($ClusterLine) ?>;
</script>

Then those variables are accessible to subsequent javascript.

Answer:

This is how can you generate data dynamically from PHP, generate a JSON formatted output properly and read it from JavaScript (JQuery required) and load it to Google Visulization (Charts) API.

PHP (Server) Side:

function returnData() {
    $data = Array ();
    $data [] = Array ("Name", "Value");
    $data [] = Array ("Apple", 5);
    $data [] = Array ("Banana", 3);

    header('content-type: application/json');
    echo json_encode($data);
 }

Javascript (Client) Side:

var jsonData = null;

var jsonDataResult = $.ajax({
    url: dataURL,
    dataType: "json",
    async: false,
    success: (
        function(data) {
            jsonData = data;
        })
});

var data = new google.visualization.arrayToDataTable(jsonData);

Answer:

This is one of the best examples I did which can help you : its tested and working nicely : Create two pages one called index.php and another one called get_json.php :
This is not exactly the codes you posted but exactly the same idea and it answers the quetion.

the codes for index.php 

    <html>
    <head>
        <title>King Musa Graph</title>
        <!-- Load jQuery -->
        <script language="javascript" type="text/javascript" 
            src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js">
        </script>
        <!-- Load Google JSAPI -->
        <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 jsonData = $.ajax({
                    url: "get_json.php",
                    dataType: "json",
                    async: false
                }).responseText;

                var obj = jQuery.parseJSON(jsonData);
                var data = google.visualization.arrayToDataTable(obj);

                var options = {
                    title: 'King Musa'
                };

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

        </script>
    </head>
    <body>
        <div id="chart_div" style="width: 900px; height: 500px;">
        </div>
    </body>
    </html> 

codes for get_json.php
<?php

    $data = Array ();
    $data [] = Array ("Name", "Value");
    $data [] = Array ("PHP", 78);

    $data [] = Array ("JAVA", 1000);
  $data [] = Array ("HTML", 129);


    $table = json_encode($data);
   // header('content-type: application/json'); 

    echo $table ; // this line is important it should be not disabled 

?>