0
votes

Been looking around the web, but not found anything so far... can anyone help?

I have created a simple html page that contains a list-box of values that when selected calls a seperate php script to run database query and print out a structure html page. This has been implemented using ajax calls and it results in the page being reloaded when the user changes the value in the list-box.

Now, I would like to move away from the generating of the table using html tags and print statemetns to something more slick and have discovered google visualisation api. I have look ready through many pages of the site and used the code playground, but was unable to find information to help me understand how I might use the visualization api to generate the table and pass this back to the main page in the div tag, using the same php script.

Does anyone have any pointers, or experience of doing this in the past?

Thanks.

1

1 Answers

7
votes

You could achieve this using jQuery AJAX and some arrays generated by your php. This is a pretty basic but straightforward approach - you may want to look around for php client libraries that generate gviz code for you in your php if this proves to be insufficient.

Here's a working example:

HTML file

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="content-type" content="text/html; charset=utf-8"/>
    <script type="text/javascript" src="http://www.google.com/jsapi"></script>
    <script type="text/javascript">
      google.load("jquery", "1.6.1");
      google.load('visualization', '1', {packages: ['table']});
    </script>
    <script type="text/javascript">

    function drawVisualization(dataFromAjax) {
      var data = google.visualization.arrayToDataTable(dataFromAjax);
      visualization = new google.visualization.Table(document.getElementById('table'));
      visualization.draw(data);
    }

    function makeAjaxCall() {
      $.ajax({url:'test.php',
              data: {},
              success: function(responseData) {
                         // eval just for testing - make safer
                         var arrayForGviz = eval("(" + responseData + ")");
                         drawVisualization(arrayForGviz);
                       }
        });
    }
    </script>
  </head>
  <body>
    <input type="button" onclick="makeAjaxCall();return false;" value="Click to get data"></input>
    <div id="table"></div>
  </body>
</html>
​

PHP File

<?php
echo "[['Country','City','Value'],
       ['Ireland','Dublin','10'],
       ['France','Paris','15']]"
?>

Obviously my php file is static, but each time the user interacts with the page and triggers makeAjaxCall() you could send different parameters, and return different array responses.