Using PHP to Populate Google Charts Data Breaks Interactivity - php

I am currently using Google Charts with PHP to populate the data but the interactivity of the chart ceases to work and I don't know why.
The code is as follows:
<?php
// Connect to DB and execute while loop to get values
...
...
echo '<div id="chart_div"></div>';
?>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript">
// Load the Visualization API and the piechart package.
google.load('visualization', '1.0', {'packages':['corechart']});
// Set a callback to run when the Google Visualization API is loaded.
google.setOnLoadCallback(drawChart);
// Callback that creates and populates a data table,
// instantiates the pie chart, passes in the data and
// draws it.
function drawChart() {
// Create the data table.
var data = new google.visualization.DataTable();
data.addColumn('string', 'Review Score');
data.addColumn('number', 'Number of Reviews');
data.addRows([
['1 Star Reviews', <?php echo $one; ?>],
['2 Star Reviews', <?php echo $two; ?>],
['3 Star Reviews', <?php echo $three; ?>],
['4 Star Reviews', <?php echo $four; ?>],
['5 Star Reviews', <?php echo $five; ?>]
]);
// Set chart options
var options = {'title':'Breakdown of Review Scores',
'is3D':true,
'width':600,
'height':400};
// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
Even if I move the chart_div to after the javascript it doesn't work.
Incase anyone asks the the js isn't in the head tags it's because I am also displaying a table populated with the results of the sql query and calculating totals based off those results for use in the chart.
I have since found this page but don't see why that would alter anything:
https://developers.google.com/chart/interactive/docs/php_example

I meant to update a lot sooner but the problem lay elsewhere - Google Charts works perfectly fine when using php to populate the chart data.

Related

php variables on google chart [duplicate]

This question already has an answer here:
Google Chart From Php variable
(1 answer)
Closed 6 years ago.
i have google charts working but need to pass the variables to its javascript builder, i tried to use $var inside javascript but it dont work.......
i have :
script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Estrelas', 'Pontuação'],
['1 estrelas', $ums],
['2 estrelas', $doiss],
['3 estrelas', $tress],
['3 estrelas', $quatros],
['5 estrela', $cincos]
]);
var options = {
title: 'My Daily Activities'
};
var chart = new google.visualization.PieChart(document.getElementById('piechart'));
chart.draw(data, options);
}
</script>
You have to encapsulate the PHP vars, like:
['1 estrelas', <? echo $ums?> ],
or if your PHP config accepts short tags
['1 estrelas', <?= $ums ?> ],
Try putting PHP tags around it, for example:
['1 estrelas', $ums] becomes ['1 estrelas', <?php echo $ums; ?>],

Google Pie Charts and PHP

I would like to have a Google pie chart on my website. The pie chart would be filled with data from the database. I was loooking at some examples at https://developers.google.com/chart/interactive/docs/php_example, but I'm lost when it comes to the JSON format.
Here are some examples:
<html>
<head>
<!--Load the AJAX API-->
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript" src="jquery-1.6.2.min.js"></script>
<script type="text/javascript">
// Load the Visualization API and the piechart package.
google.load('visualization', '1', {'packages':['corechart']});
// Set a callback to run when the Google Visualization API is loaded.
google.setOnLoadCallback(drawChart);
function drawChart() {
var jsonData = $.ajax({
url: "getData.php",
dataType:"json",
async: false
}).responseText;
// Create our data table out of JSON data loaded from server.
var data = new google.visualization.DataTable(jsonData);
// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
chart.draw(data, {width: 400, height: 240});
}
</script>
</head>
<body>
<!--Div that will hold the pie chart-->
<div id="chart_div"></div>
</body>
</html>
And here is the snippet where I get lost (getData.php):
<?php
// This is just an example of reading server side data and sending it to the client.
// It reads a json formatted text file and outputs it.
$string = file_get_contents("sampleData.json");
echo $string;
// Instead you can query your database and parse into JSON etc etc
?>
I have data stored in a database and not in JSON format. How do I work with the JSON format using MySQL database queries? If you have some examples or demos, I would appreciate it.
The first thing to do would be to have a look at the PHP manual about the json_encode() method. It provides examples on how to generate JSON with PHP.
Here is a short example from another similar SO question:
// Get your data from DB
$sth = mysql_query("SELECT ...");
// Create an array
$rows = array();
// Loop over the DB result and add it to your array
while($r = mysql_fetch_assoc($sth)) {
$rows[] = $r;
}
// Use json_encode() to turn the array into JSON
print json_encode($rows);
If you need to rename your database columns, so that your JSON-data get other names on the properties than those used in your DB, you can use AS in your SQL.
SELECT blog_title as title ...
just echo php result in
var data = new google.visualization.DataTable([<?php echo $result ;?>]);
u will get data from database as per as
below format
['Task', 'Hours per Day'],
['Work', 11],
['Eat', 2],
['Commute', 2],
['Watch TV', 2],
['Sleep', 7]
i think it's useful to u ,i am use same logic in heat map

how to work with dynamic data and google charts?

For example we have this line chart at Google Code API
there is a defined set of data which this chart reflects, however i want to create the chart using my own data from php/mysql scripting.
Here is the code provided by google to embed into html page..
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<title>
Google Visualization API Sample
</title>
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load('visualization', '1', {packages: ['imagelinechart']});
</script>
<script type="text/javascript">
function drawVisualization() {
// Create and populate the data table.
var data = new google.visualization.DataTable();
data.addColumn('string', 'Name');
data.addColumn('number', 'Height');
data.addRows(3);
data.setCell(0, 0, 'Tong Ning mu');
data.setCell(1, 0, 'Huang Ang fa');
data.setCell(2, 0, 'Teng nu');
data.setCell(0, 1, 174);
data.setCell(1, 1, 523);
data.setCell(2, 1, 86);
// Create and draw the visualization.
new google.visualization.ImageLineChart(document.getElementById('visualization')).
draw(data, null);
}
google.setOnLoadCallback(drawVisualization);
</script>
</head>
<body style="font-family: Arial;border: 0 none;">
<div id="visualization" style="width: 300px; height: 300px;"></div>
</body>
</html>
The option i have in my mind is to keep the following piece of code in a loop and generate the data. Does someone have something easy and efficient way to do this?
data.addColumn('string', 'Name');
data.addColumn('number', 'Height');
data.addRows(3);
data.setCell(0, 0, 'Tong Ning mu');
data.setCell(1, 0, 'Huang Ang fa');
data.setCell(2, 0, 'Teng nu');
data.setCell(0, 1, 174);
data.setCell(1, 1, 523);
data.setCell(2, 1, 86);
Your question touches on something that's frustrated me a lot: Google's API documentation isn't great! In particular, for Charts API, in basically all of their examples, the data for their chart is hard coded in the page, and, in real life, you'll basically always be rendering data stored in a DB and transmitted to the browser.
1) You need some code on the server (I use PHP) that queries the database, "prints" and transmits the JSON/complex data structure which is an object where the properties are arrays that contain additional objects with properties and values in the exact format that Google's Chart JavaScript expects to receive it in the browser. I did it like this:
$sql = "SELECT year,d_pop FROM metrics WHERE year IN ('1940','1950','1960','1970','1980')";
$sth = mysql_query($sql, $conn) or die(mysql_error());
//start the json data in the format Google Chart js/API expects to recieve it
$JSONdata = "{
\"cols\": [
{\"label\":\"Year\",\"type\":\"string\"},
{\"label\":\"Detroit Population\",\"type\":\"number\"}
],
\"rows\": [";
//loop through the db query result set and put into the chart cell values
while($r = mysql_fetch_assoc($sth)) {
$JSONdata .= "{\"c\":[{\"v\": " . $r['year'] . "}, {\"v\": " . $r['d_pop'] ."}]},";
}
//end the json data/object literal with the correct syntax
$JSONdata .= "]}";
echo $JSONdata;
2) You need to receive that JSON object in your JavaScript on your page and pass it to Google's Chart JS. I brought in JQuery and then used it's AJAX method like this:
function drawChart() {
var jsonData = $.ajax({
url: "index_db.php",
dataType:"json",
async: false
}).responseText;
// Create our data table out of JSON data loaded from server.
var data = new google.visualization.DataTable(jsonData);
// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, {vAxis: {minValue: 0}});
}
My code snippets focus on the key parts of querying the mySQL DB, generating the JSON object Google Charts API needs, and receiving it with JQuery and AJAX. Hope this illuminates!
You can pass data as json instead making loop and passing with data.setCell()
At php side make your data json format. Using json_encode(). And on Api use this method to pass data. Check this link for more information
http://code.google.com/apis/chart/interactive/docs/reference.html#DataTable_toJSON

How to add events in Google Charts when the data source is from a PHP/MySQL file?

I'm creating charts using Google Charts API. Im using PHP/MySQL as my data source using this code.
<html>
<head>
<!--Load the AJAX API-->
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.6.2.min.js"></script>enter code here
<script type="text/javascript">
// Load the Visualization API and the piechart package.
google.load('visualization', '1', {'packages':['corechart']});
// Set a callback to run when the Google Visualization API is loaded.
google.setOnLoadCallback(drawChart);
function drawChart() {
var jsonData = $.ajax({
url: "getData.php",
dataType:"json",
async: false
}).responseText;
// Create our data table out of JSON data loaded from server.
var data = new google.visualization.DataTable(jsonData);
// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
chart.draw(data, {width: 600, height: 440, is3D:true});
}
</script>
</head>
<body>
<!--Div that will hold the pie chart-->
<div id="chart_div"></div>
</body>
</html>
The code is working. My Question is, Is it possible to insert events here when I'm using data from MySQL dsiplaying as JSON format in PHP? How can I change the data when the data source that I'm referring from is from another file (in this case, getData.php). In a simple explanation, if this code shows that the number of trees in 2011 is 300,000...How can I change that value if I have a value of 400,000 for 2012 in a click of a button or from a drop down selection. I hope you get what I'm asking.
thanks in advance.
Here are the codes I used:
getData.php
<?php
// This is just an example of reading server side data and sending it to the client.
// It reads a json formatted text file and outputs it.
$string = file_get_contents("sampleData.json");
echo $string;
?>
sampleData.JSON
{
"cols": [
{"id":"","label":"Topping","pattern":"","type":"string"},
{"id":"","label":"Slices","pattern":"","type":"number"}
],
"rows": [
{"c":[{"v":"Mushrooms","f":null},{"v":3,"f":null}]},
{"c":[{"v":"Onions","f":null},{"v":1,"f":null}]},
{"c":[{"v":"Olives","f":null},{"v":1,"f":null}]},
{"c":[{"v":"Zucchini","f":null},{"v":1,"f":null}]},
{"c":[{"v":"Pepperoni","f":null},{"v":2,"f":null}]}
]
}

Google Area Chart

Im trying to using Google Area Chart and PHP to display some data. problem is i just cant get it to work. if anyone can help it will be most appriciated.
Here is my code:
<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', 'Date');
data.addColumn('number', 'hits');
data.addRows([
<?php
$query = mysql_query("SELECT * FROM hits WHERE url='$url' GROUP BY date");
while ($row = mysql_fetch_array($query)){
$hits=mysql_num_rows($query);
$date=$row['date'];?>
['<?php echo "$date";?>', <?php echo ".$hits.";?>],
<?php } ?>
]);
var chart = new google.visualization.AreaChart(document.getElementById('chart_div'));
chart.draw(data, {width: 400, height: 240, title: 'Company Performance',
hAxis: {title: 'Date', titleTextStyle: {color: '#FF0000'}}
});
}
</script>
<div id="chart_div"></div>
I would definitely suggest separating your PHP (server side) code from your JavaScript/html (client side) code.
The nice thing about the Google chart and graph APIs is there are several examples one can draw from, but it becomes much harder to reproduce something you're viewing when you embed PHP with MySQL queries within the blocks that contain your JavaScript and UI elements.
The following is a rough example of how you "might" go about dividing these things. In reality you would want your server side code (PHP in your case) in a totally separate file from your display/user interface code (HTML and JavaScript).
The 'DATE' and 'HITS' in the "Front end code" block are not actually variables or values, I'm simply indicating this is where you would input your values. Ideally you would pass the data from your MySQL query through the PHP server code to the JavaScript code, and then iterate through it there to build your graph. The passing things back and forth from PHP to JS can be done nicely using the JSON data interchange format. Both PHP and JavaScript (jQuery) have functions for encoding and decoding to/from JSON.
Front End Code:
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Date');
data.addColumn('number', 'hits');
data.addRows(
['DATE', 'HITS']
);
var chart = new google.visualization.AreaChart(document.getElementById('chart_div'));
chart.draw(data, {width: 400, height: 240, title: 'Company Performance',
hAxis: {title: 'Date', titleTextStyle: {color: '#FF0000'}}
});
}
</script>
<div id="chart_div"></div>
Back End Code:
<?php
$query = mysql_query("SELECT * FROM hits WHERE url='$url' GROUP BY date");
$data_to_return = array();
while ($row = mysql_fetch_array($query))
{
$hits=mysql_num_rows($query);
$date=$row['date'];
$data_to_return[$date] = $hits; //building array of date=>hits data
}
$data_to_send_to_front_end = json_encode($data_to_return); //ridiculous variable name
?>

Categories