Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed last year.
Locked. This question and its answers are locked because the question is off-topic but has historical significance. It is not currently accepting new answers or interactions.
I have searched a lot to find a good example for generating a Google Chart using MySQL table data as the data source. I searched for a couple of days and realised that there are few examples available for generating a Google Chart (pie, bar, column, table) using a combination of PHP and MySQL. I finally managed to get one example working.
I have previously received a lot of help from StackOverflow, so this time I will return some.
I have two examples; one uses Ajax and the other does not. Today, I will only show the non-Ajax example.
Usage:
Requirements: PHP, Apache and MySQL
Installation:
--- Create a database by using phpMyAdmin and name it "chart"
--- Create a table by using phpMyAdmin and name it "googlechart" and make
sure table has only two columns as I have used two columns. However,
you can use more than 2 columns if you like but you have to change the
code a little bit for that
--- Specify column names as follows: "weekly_task" and "percentage"
--- Insert some data into the table
--- For the percentage column only use a number
---------------------------------
example data: Table (googlechart)
---------------------------------
weekly_task percentage
----------- ----------
Sleep 30
Watching Movie 10
job 40
Exercise 20
PHP-MySQL-JSON-Google Chart Example:
<?php
$con=mysql_connect("localhost","Username","Password") or die("Failed to connect with database!!!!");
mysql_select_db("Database Name", $con);
// The Chart table contains two fields: weekly_task and percentage
// This example will display a pie chart. If you need other charts such as a Bar chart, you will need to modify the code a little to make it work with bar chart and other charts
$sth = mysql_query("SELECT * FROM chart");
/*
---------------------------
example data: Table (Chart)
--------------------------
weekly_task percentage
Sleep 30
Watching Movie 40
work 44
*/
//flag is not needed
$flag = true;
$table = array();
$table['cols'] = array(
// Labels for your chart, these represent the column titles
// Note that one column is in "string" format and another one is in "number" format as pie chart only required "numbers" for calculating percentage and string will be used for column title
array('label' => 'Weekly Task', 'type' => 'string'),
array('label' => 'Percentage', 'type' => 'number')
);
$rows = array();
while($r = mysql_fetch_assoc($sth)) {
$temp = array();
// the following line will be used to slice the Pie chart
$temp[] = array('v' => (string) $r['Weekly_task']);
// Values of each slice
$temp[] = array('v' => (int) $r['percentage']);
$rows[] = array('c' => $temp);
}
$table['rows'] = $rows;
$jsonTable = json_encode($table);
//echo $jsonTable;
?>
<html>
<head>
<!--Load the Ajax API-->
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.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() {
// Create our data table out of JSON data loaded from server.
var data = new google.visualization.DataTable(<?=$jsonTable?>);
var options = {
title: 'My Weekly Plan',
is3D: 'true',
width: 800,
height: 600
};
// Instantiate and draw our chart, passing in some options.
// Do not forget to check your div ID
var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
</head>
<body>
<!--this is the div that will hold the pie chart-->
<div id="chart_div"></div>
</body>
</html>
PHP-PDO-JSON-MySQL-Google Chart Example:
<?php
/*
Script : PHP-PDO-JSON-mysql-googlechart
Author : Enam Hossain
version : 1.0
*/
/*
--------------------------------------------------------------------
Usage:
--------------------------------------------------------------------
Requirements: PHP, Apache and MySQL
Installation:
--- Create a database by using phpMyAdmin and name it "chart"
--- Create a table by using phpMyAdmin and name it "googlechart" and make sure table has only two columns as I have used two columns. However, you can use more than 2 columns if you like but you have to change the code a little bit for that
--- Specify column names as follows: "weekly_task" and "percentage"
--- Insert some data into the table
--- For the percentage column only use a number
---------------------------------
example data: Table (googlechart)
---------------------------------
weekly_task percentage
----------- ----------
Sleep 30
Watching Movie 10
job 40
Exercise 20
*/
/* Your Database Name */
$dbname = 'chart';
/* Your Database User Name and Passowrd */
$username = 'root';
$password = '123456';
try {
/* Establish the database connection */
$conn = new PDO("mysql:host=localhost;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
/* select all the weekly tasks from the table googlechart */
$result = $conn->query('SELECT * FROM googlechart');
/*
---------------------------
example data: Table (googlechart)
--------------------------
weekly_task percentage
Sleep 30
Watching Movie 10
job 40
Exercise 20
*/
$rows = array();
$table = array();
$table['cols'] = array(
// Labels for your chart, these represent the column titles.
/*
note that one column is in "string" format and another one is in "number" format
as pie chart only required "numbers" for calculating percentage
and string will be used for Slice title
*/
array('label' => 'Weekly Task', 'type' => 'string'),
array('label' => 'Percentage', 'type' => 'number')
);
/* Extract the information from $result */
foreach($result as $r) {
$temp = array();
// the following line will be used to slice the Pie chart
$temp[] = array('v' => (string) $r['weekly_task']);
// Values of each slice
$temp[] = array('v' => (int) $r['percentage']);
$rows[] = array('c' => $temp);
}
$table['rows'] = $rows;
// convert data into JSON format
$jsonTable = json_encode($table);
//echo $jsonTable;
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
?>
<html>
<head>
<!--Load the Ajax API-->
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.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() {
// Create our data table out of JSON data loaded from server.
var data = new google.visualization.DataTable(<?=$jsonTable?>);
var options = {
title: 'My Weekly Plan',
is3D: 'true',
width: 800,
height: 600
};
// Instantiate and draw our chart, passing in some options.
// Do not forget to check your div ID
var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
</head>
<body>
<!--this is the div that will hold the pie chart-->
<div id="chart_div"></div>
</body>
</html>
PHP-MySQLi-JSON-Google Chart Example
<?php
/*
Script : PHP-JSON-MySQLi-GoogleChart
Author : Enam Hossain
version : 1.0
*/
/*
--------------------------------------------------------------------
Usage:
--------------------------------------------------------------------
Requirements: PHP, Apache and MySQL
Installation:
--- Create a database by using phpMyAdmin and name it "chart"
--- Create a table by using phpMyAdmin and name it "googlechart" and make sure table has only two columns as I have used two columns. However, you can use more than 2 columns if you like but you have to change the code a little bit for that
--- Specify column names as follows: "weekly_task" and "percentage"
--- Insert some data into the table
--- For the percentage column only use a number
---------------------------------
example data: Table (googlechart)
---------------------------------
weekly_task percentage
----------- ----------
Sleep 30
Watching Movie 10
job 40
Exercise 20
*/
/* Your Database Name */
$DB_NAME = 'chart';
/* Database Host */
$DB_HOST = 'localhost';
/* Your Database User Name and Passowrd */
$DB_USER = 'root';
$DB_PASS = '123456';
/* Establish the database connection */
$mysqli = new mysqli($DB_HOST, $DB_USER, $DB_PASS, $DB_NAME);
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
/* select all the weekly tasks from the table googlechart */
$result = $mysqli->query('SELECT * FROM googlechart');
/*
---------------------------
example data: Table (googlechart)
--------------------------
Weekly_Task percentage
Sleep 30
Watching Movie 10
job 40
Exercise 20
*/
$rows = array();
$table = array();
$table['cols'] = array(
// Labels for your chart, these represent the column titles.
/*
note that one column is in "string" format and another one is in "number" format
as pie chart only required "numbers" for calculating percentage
and string will be used for Slice title
*/
array('label' => 'Weekly Task', 'type' => 'string'),
array('label' => 'Percentage', 'type' => 'number')
);
/* Extract the information from $result */
foreach($result as $r) {
$temp = array();
// The following line will be used to slice the Pie chart
$temp[] = array('v' => (string) $r['weekly_task']);
// Values of the each slice
$temp[] = array('v' => (int) $r['percentage']);
$rows[] = array('c' => $temp);
}
$table['rows'] = $rows;
// convert data into JSON format
$jsonTable = json_encode($table);
//echo $jsonTable;
?>
<html>
<head>
<!--Load the Ajax API-->
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.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() {
// Create our data table out of JSON data loaded from server.
var data = new google.visualization.DataTable(<?=$jsonTable?>);
var options = {
title: 'My Weekly Plan',
is3D: 'true',
width: 800,
height: 600
};
// Instantiate and draw our chart, passing in some options.
// Do not forget to check your div ID
var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
</head>
<body>
<!--this is the div that will hold the pie chart-->
<div id="chart_div"></div>
</body>
</html>
Some might encounter this error either locally or on the server:
syntax error var data = new google.visualization.DataTable(<?=$jsonTable?>);
This means that their environment does not support short tags the solution is to use this instead:
<?php echo $jsonTable; ?>
And everything should work fine!
You can do this more easy way. And 100% works that you want
<?php
$servername = "localhost";
$username = "root";
$password = ""; //your database password
$dbname = "demo"; //your database name
$con = new mysqli($servername, $username, $password, $dbname);
if ($con->connect_error) {
die("Connection failed: " . $con->connect_error);
}
else
{
//echo ("Connect Successfully");
}
$query = "SELECT Date_time, Tempout FROM alarm_value"; // select column
$aresult = $con->query($query);
?>
<!DOCTYPE html>
<html>
<head>
<title>Massive Electronics</title>
<script type="text/javascript" src="loder.js"></script>
<script type="text/javascript">
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart(){
var data = new google.visualization.DataTable();
var data = google.visualization.arrayToDataTable([
['Date_time','Tempout'],
<?php
while($row = mysqli_fetch_assoc($aresult)){
echo "['".$row["Date_time"]."', ".$row["Tempout"]."],";
}
?>
]);
var options = {
title: 'Date_time Vs Room Out Temp',
curveType: 'function',
legend: { position: 'bottom' }
};
var chart = new google.visualization.AreaChart(document.getElementById('areachart'));
chart.draw(data, options);
}
</script>
</head>
<body>
<div id="areachart" style="width: 900px; height: 400px"></div>
</body>
</html>
loder.js link here loder.js
use this, it realy works:
data.addColumn no of your key, you can add more columns or remove
<?php
$con=mysql_connect("localhost","USername","Password") or die("Failed to connect with database!!!!");
mysql_select_db("Database Name", $con);
// The Chart table contain two fields: Weekly_task and percentage
//this example will display a pie chart.if u need other charts such as Bar chart, u will need to change little bit to make work with bar chart and others charts
$sth = mysql_query("SELECT * FROM chart");
while($r = mysql_fetch_assoc($sth)) {
$arr2=array_keys($r);
$arr1=array_values($r);
}
for($i=0;$i<count($arr1);$i++)
{
$chart_array[$i]=array((string)$arr2[$i],intval($arr1[$i]));
}
echo "<pre>";
$data=json_encode($chart_array);
?>
<html>
<head>
<!--Load the AJAX API-->
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.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() {
// Create our data table out of JSON data loaded from server.
var data = new google.visualization.DataTable();
data.addColumn("string", "YEAR");
data.addColumn("number", "NO of record");
data.addRows(<?php $data ?>);
]);
var options = {
title: 'My Weekly Plan',
is3D: 'true',
width: 800,
height: 600
};
// Instantiate and draw our chart, passing in some options.
//do not forget to check ur div ID
var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
</head>
<body>
<!--Div that will hold the pie chart-->
<div id="chart_div"></div>
</body>
</html>
Related
I'm trying to display information from my SQL database to google charts.
The project is a health dashboard where I need to display steps, kcal, etc.
I got the information from the database but I'm having trouble looping over it (the same information displays multiple times). I assume the problem is somewhere at the "data.addrows"-code.
php
include('template.php');
$query = /** #lang text */ <<
SELECT * FROM project_healthinfo WHERE id = {$_SESSION['userId']} ORDER BY date DESC
END;
$res = $mysqli->query($query);
$result = $res->fetch_object();
$content = <<<END
<!-- Google Chart script starts here -->
<!--Load the AJAX API-->
// Load the Visualization API and the corechart package.
google.charts.load('current', {'packages':['corechart']});
// Set a callback to run when the Google Visualization API is loaded.
google.charts.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.
google.charts.load('current', {'packages':['line']});
google.charts.setOnLoadCallback(drawChart);
google.charts.load('current', {'packages':['line']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Date');
data.addColumn('number', 'Steps taken');
data.addRows([
['$result->date', $result->steps],
['$result->date', $result->steps],
['$result->date', $result->steps]
]);
var options = {
chart: {
title: ''
},
width: 550,
height: 300
};
var chart = new google.charts.Line(document.getElementById('steps_chart'));
chart.draw(data, google.charts.Line.convertOptions(options));
}
</script>
<!-- Google Chart script ends here -->
You'll need to break the $content into two parts.
$before_result_date = <<<EOS
...
EOS;
$after_result_data = <<<EOQ
...
EOS;
Then the section between there should be a loop similar to this.
while($result = $mysqli->fetch_object()){
printf("['%s', %s],\n",$result->date, $result->steps);
}
and all together it would be something like this:
include('template.php');
$query = /** #lang text */ <<
SELECT * FROM project_healthinfo WHERE id =
{$_SESSION['userId']} ORDER BY date DESC
END;
$res = $mysqli->query($query);
print $before_result_date;
while($result = $mysqli->fetch_object()){
printf("['%s', %s],\n",$result->date, $result->steps);
}
print $after_result_date;
That should do it.
I am pulling data from a database via mysqli to create a Google pie Chart. The data is from one column (a1), but each entry is different (eg, a, b, c) and I am listing the percentage of responses for each entry/answer.
So for instance,
a = 20%
b = 30%
Each entry corresponds to a different social media type, which I need to show but is not shown in the database itself. Is there a way to change the legend of the chart so that instead of listing A, B, C it would replace that with a custom label? (Eg, instead of showing 'A' show 'Facebook').
my column
my current chart
I have tried using title under var data, label under options, legend under options. I feel like I'm missing something
<?php
$connect = mysqli_connect("localhost", "root", "root", "survey");
$query = "SELECT a1, count(*) as number FROM rtp2k GROUP BY a1";
$result = mysqli_query($connect, $query);
?>
<!DOCTYPE html>
<html>
<head>
<title>Sad me is Sad </title>
<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([
['social', 'number'],
<?php
while($row = mysqli_fetch_array($result))
{
echo "['".$row["a1"]."', ".$row["number"]."],";
}
?>
]);
var options = {
title: 'Which social networks do you use most often?',
//is3D:true,
pieHole: 0.4,
};
var chart = new google.visualization.PieChart(document.getElementById('piechart'));
chart.draw(data, options);
}
</script>
</head>
<body>
<br /><br />
<div style="width:900px;">
<h3 align="center">Make Simple Pie Chart by Google Chart API with PHP Mysql</h3>
<br />
<div id="piechart" style="width: 900px; height: 500px;">
</div>
</div>
</body>
</html>
Right now my legend lists the type by what is in the database, (eg, a, b, c) I would like to replace the letters with my own label/title (eg, instead of 'a', I would like it to say 'Facebook'.
Edited for consistency.
we can use a DataView with a calculated column,
to convert the values the network names.
first, create an object to map the values to the names.
var socialNetworks = {
a: 'Facebook',
b: 'Instagram',
c: 'LinkedIn'
};
then we create a DataView from the DataTable.
var view = new google.visualization.DataView(data);
then use method setColumns to add a calculated column for the conversion.
we use the column index of the number, since it won't be changing.
view.setColumns([{
calc: function (dt, row) {
return socialNetworks[data.getValue(row, 0)];
},
label: 'social',
type: 'string'
}, 1]);
then use the DataView to draw the chart.
chart.draw(view, options);
full snippet...
var data = google.visualization.arrayToDataTable([
['social', 'number'],
<?php
while($row = mysqli_fetch_array($result))
{
echo "['".$row["a1"]."', ".$row["number"]."],";
}
?>
]);
var options = {
title: 'Which social networks do you use most often?',
//is3D:true,
pieHole: 0.4,
};
var socialNetworks = {
a: 'Facebook',
b: 'Instagram',
c: 'LinkedIn'
};
var view = new google.visualization.DataView(data);
view.setColumns([{
calc: function (dt, row) {
return socialNetworks[data.getValue(row, 0)];
},
label: 'social',
type: 'string'
}, 1]);
var chart = new google.visualization.PieChart(document.getElementById('piechart'));
chart.draw(view, options);
I set two variable in date format then i put it in the sql query to find data between two dates and to show them as column chart. But its not working. without script code it shows proper data but when i include script for column it doesn't display any output any suggestion?
Here is the code:
<?php
$user='root';
$pass='';
$db='mypro_bms';
$conn = mysqli_connect('localhost',$user,$pass,$db);
$count=0;
if(isset($_POST['search'])){
$txtStartDate = date('Y-m-d',strtotime($_POST['txtStartDate']));;
$txtEndDate = date('Y-m-d',strtotime($_POST['txtEndDate']));;
$q=mysqli_query($conn,"SELECT blood_group, SUM(blood_bag) as sum FROM donate where date(donation_date)between'$txtStartDate' and '$txtEndDate' group by blood_group");
$count=mysqli_num_rows($q);
}
?>
<html>
<head>
<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([
['sum','blood_group'],
<?php
if ($count=="0")
{
echo "No data"; }
else
{
while ($row=$q->fetch_assoc()) {
echo"['".$row['blood_group']."',".$row['sum']."],";
}
}
?>
]);
var options = {
title: 'Blood volume',
is3D: true,
};
var chart = new google.visualization.ColumnChart(document.getElementById('piechart'));
chart.draw(data, options);
}
</script>
</head>
I'm fairly new to the coding world so please have mercy regarding my obsolete SQL connection although the wpdp class does exist. I am aware of this, but for some reasons, it doesn't work and that's another topic...
I try to write my own plugin to connect to my sql database, query some stuff and then provide a google chart with a jsontable. The code works If I use it in a stand alone .php file. However, as soon as I activate do_action nothing works and my whole page is white.
<?php
/*
Plugin Name: mm_gchart
Description: -
Version: 1.0.0
Author: MM
*/
function mm_gct_data() {
$con=mysqli_connect("localhost","xx","xx","xx");
// Check connection
if (mysqli_connect_errno()) {
//echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
//echo "Hello";
$sql="SELECT gewicht, wdh FROM testtable";
$query=mysqli_query($con, $sql);
$rows=array();
$table=array();
$table['cols'] = array(
array('label' => 'Gewicht', 'type' => 'number'),
array('label' => 'Wiederholungen', 'type' => 'number')
);
while ($r = mysqli_fetch_assoc($query))
{
$temp=array();
$temp[]=array('v' => (int) $r['gewicht']);
$temp[]=array('v' => (int) $r['wdh']);
$rows[]=array('c' => $temp);
}
global $jsonTable;
$table['rows'] = $rows;
$jsonTable = json_encode($table);
}
add_action('init', 'mm_gct_data');
//do_action( 'init','mm_gct_data' );
?>
I would be super happy, if somebody could work some black magic on my code and then provide a simple description.
Thanks in advance!
Edit after replies:
Thank you very much for your fast reply! If the do_action() command was not the reason for my blank page, then what is?
<html>
<head>
<!--Load the AJAX API-->
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.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() {
// Create our data table out of JSON data loaded from server.
var data = new google.visualization.DataTable(<?=$jsonTable?>);
var options = {
title: 'Testing',
width: 600,
height: 400
};
// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
</head>
<body>
<!--Div that will hold the pie chart-->
<div id="chart_div"></div>
<p>Everything went well..</p>
</body>
</html>
You should not make a call to do_action() as you have it in your code. This action hook is built into WordPress and will be called automatically as part of its running. The WordPress site has a list of the Actions Run During a Typical Request on their site.
It is appropriate to make a call to do_action() when you want to implement a custom action hook for other developers to plug in to. Calls to add_action() can be made to add events to your hook.
I'm trying to generate a google chart from mysql data using php.
Here is my code so far :
get_json.php
<?php
/* $server = the IP address or network name of the server
* $userName = the user to log into the database with
* $password = the database account password
* $databaseName = the name of the database to pull data from
* table structure - colum1 is cas: has text/description - column2 is data has the value
*/
$con = mysql_connect('localhost','root','') ;
mysql_select_db('gcm', $con);
// write your SQL query here (you may use parameters from $_GET or $_POST if you need them)
$query = mysql_query('SELECT count(name) As Subscribers,CAST(`created_at` AS DATE) As Date FROM gcm_users GROUP BY created_at ORDER BY created_at')or die(mysql_error());
$table = array();
$table['cols'] = array(
/* define your DataTable columns here
* each column gets its own array
* syntax of the arrays is:
* label => column label
* type => data type of column (string, number, date, datetime, boolean)
*/
// I assumed your first column is a "string" type
// and your second column is a "number" type
// but you can change them if they are not
array('label' => 'Date', 'type' => 'string'),
array('label' => 'Subscribers', 'type' => 'number')
);
$rows = array();
while($r = mysql_fetch_assoc($query)) {
$temp = array();
// each column needs to have data inserted via the $temp array
$temp[] = array('v' => $r['Date']);
$temp[] = array('v' => (int) $r['Subscribers']);
// insert the temp array into $rows
$rows[] = array('c' => $temp);
}
// populate the table with rows of data
$table['rows'] = $rows;
// encode the table as JSON
$jsonTable = json_encode($table);
// set up header; first two prevent IE from caching queries
header('Cache-Control: no-cache, must-revalidate');
header('Content-type: application/json');
// return the JSON data
echo $jsonTable;
?>
It displays right : {"cols":[{"label":"Date","type":"string"},{"label":"Subscribers","type":"number"}],"rows":[{"c":[{"v":"2013-04-14"},{"v":1}]},{"c":[{"v":"2013-04-15"},{"v":1}]}]}
This is where I display :
<!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"/>
<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: ['corechart']});
</script>
<script type="text/javascript">
function drawVisualization() {
var jsonData = null;
var json = $.ajax({
url: "get_json.php", // make this url point to the data file
dataType: "json",
async: false,
success: (
function(data) {
jsonData = data;
})
}).responseText;
// Create and populate the data table.
var data = new google.visualization.DataTable(jsonData);
// Create and draw the visualization.
var chart= new google.visualization.LineChart(document.getElementById('visualization')).
draw(data, {curveType: "function",
width: 500, height: 400,
vAxis: {maxValue: 10}}
);
}
google.setOnLoadCallback(drawVisualization);
</script>
</head>
<body style="font-family: Arial;border: 0 none;">
<div id="visualization" style="width: 500px; height: 400px;"></div>
</body>
</html>
But when i run this code I got nothing,it's blank ! Where is my error?
Now tested:
You haven't included jQuery in your page. Add this line in your <head> and it works.
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
Another thing that can happen if your AJAX call takes a little longer:
By the time your success: function() is called after the AJAX call is finished the rest of the script has already run. The script doesn't wait until the AJAX call is finished until the "Create and populate" part is executed. You have to place these lines inside the success: function().
<script type="text/javascript">
function drawVisualization() {
var jsonData = null;
var json = $.ajax({
url: "get_json.php", // make this url point to the data file
dataType: "json",
async: false,
success: (
function(data) {
jsonData = data;
// Create and populate the data table.
var data = new google.visualization.DataTable(jsonData);
// Create and draw the visualization.
var chart= new google.visualization.LineChart(document.getElementById('visualization')).
draw(data, {curveType: "function",
width: 500, height: 400,
vAxis: {maxValue: 10}}
);
})
}).responseText;
}
google.setOnLoadCallback(drawVisualization);
</script>
This way you can make sure that all relevant code is only executed after the AJAX call has finished.