Display a google chart with json & PHP - php

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.

Related

im trying to use google charts and it show me a blank page im using laravel 5.4

This is the view file I dont know what's going on please help!
<html>
<head>
<!--Load the Ajax API-->
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<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">
<script type="text/javascript">
google.charts.load('current', {'packages':['gantt']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
// Create our data table out of JSON data loaded from server.
var jsonData = $.ajax({
url: "getData.php",
dataType: "json",
async: false
}).responseText;
var options = {
height: 400,
gantt: {
trackHeight: 30
}
};
var data = new google.visualization.DataTable(jsonData);
// Instantiate and draw our chart, passing in some options.
// Do not forget to check your div ID
var chart = new google.visualization.Gantt(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
</head>
<body>
<!--this is the div that will hold the GANT chart-->
<div id="chart_div"></div>
</body>
</html>
*this the code of getData.php *
<?php
$con=mysqli_connect("localhost" , 'root' , '' , 'planification' );
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$query = "SELECT * FROM `gants` WHERE 1";
$result = mysqli_query($con,$query);
$rows = array();
while($r = mysqli_fetch_array($result)) {
$rows[] = $r;
}
echo json_encode($rows);
mysqli_close($con);
?>
file location
enter image description here
this is the content of getData file
C:\Users\ahmed\Ph-r-p>php getData.php
[{"0":"DHDJJ","Task ID":"DHDJJ","1":"DCNJNDSNDS","Task Name":"DCNJNDSNDS","2":"NDNDNS","Resource":"NDNDNS","3":"2017-04-03","Start Date":"2017-04-03","4":"2017-04-05","End Date":"2017-04-05","5":null,"Duration":null,"6":"100","Percent Complete":"100","7":null,"Dependencies":null},{"0":"dhsg","Task ID":"dhsg","1":"djbs","Task Name":"djbs","2":"djsn","Resource":"djsn","3":"2017-04-05","Start Date":"2017-04-05","4":"2017-04-08","End Date":"2017-04-08","5":null,"Duration":null,"6":"12","Percent Complete":"12","7":null,"Dependencies":null},{"0":"DKJNDES","Task ID":"DKJNDES","1":"DDNS","Task Name":"DDNS","2":"DKNS","Resource":"DKNS","3":"2017-04-09","Start Date":"2017-04-09","4":"2017-04-12","End Date":"2017-04-12","5":null,"Duration":null,"6":"10","Percent Complete":"10","7":null,"Dependencies":null},{"0":"FKSNJ","Task ID":"FKSNJ","1":"LKQSDFJ","Task Name":"LKQSDFJ","2":"QSJDH","Resource":"QSJDH","3":"2017-04-10","Start Date":"2017-04-10","4":"2017-04-14","End Date":"2017-04-14","5":null,"Duration":null,"6":"100","Percent Complete":"100","7":null,"Dependencies":null}]
In laravel, public folder is only accessible from url. So you should put getData.php in public folder. And use it like this in your ajax :
var jsonData = $.ajax({
url: "public/getData.php",
dataType: "json",
async: false
}).responseText;
It seems like you are really new to any MVC structure. You should start learning MVC and structure of laravel. You should user laravel route and controller. Here is the video series to learn laravel from scrath : https://laracasts.com/series/laravel-5-from-scratch

Style is not showing in Google org chart

$table = array();
$str = '<b>BB</b>';
$table['cols'] = array(
array("id"=>"","label"=>"Name","pattern"=>"","type"=>"string"),
array("id"=>"","label"=>"Manager","pattern"=>"","type"=>"string"),
array("id"=>"","label"=>"Tooltip","pattern"=>"","type"=>"string")
);
$rows = array();
$temp = array();
$temp[] = array("v"=>"BB","f"=>"BB");
$temp[] = array("v"=>null,"f"=>null);
$temp[] = array("v"=>null,"f"=>null);
$rows[] = array('c' => $temp,'p'=>'{style: border: 2px solid #D1D0CE;}');
$table['rows'] = $rows;
$jsonTable = json_encode($table);
echo $jsonTable;
'p'=>'{style: border: 2px solid #D1D0CE;}' this style is not showing in Google org chart.
Actually it is showing the error jQuery error "TypeError: invalid 'in' operand c
without it the org chart is showing fine. What is the proper format to give p: tag.
My client side code:
<!Doctype html>
<html>
<head>
<meta charset="utf-8">
<!--Load the AJAX API-->
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript" src="js/jquery-2.0.2.min.js"></script>
<script type="text/javascript">
// Load the Visualization API and the piechart package.
google.load('visualization', '1', {'packages': ['orgchart']});
// 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.OrgChart(document.getElementById('chart_div'));
chart.draw(data, {allowHtml: true});
}
</script>
</head>
This is my json response.
{"cols":[{"id":"","label":"Name","pattern":"","type":"string"}, {"id":"","label":"Manager","pattern":"","type":"string"},{"id":"","label":"Tooltip","pattern":"","type":"string"}],"rows":[{"c":[{"v":"BB","f":"BB"},{"v":null,"f":null},{"v":null,"f":null}],"p":"{style: 'border: 2px solid #D1D0CE;'}"}]}
Thanks in advance.

PHP arrays with Ajax - Proper way to get the data?

I'm a complete ajax/php idiot - lets get that out of the way right now; but I've gotten to a point where I need some help. I've been following various tutorials here and there and kind of putting together a report.
Ultimately I have a table that contains all the data I need. I can get that data and display it appropriately in a table without issue. I'm trying to add 'drop-down' boxes that will allow filtering based on the criteria (there is a column called 'verticals' in this table - so a dropdown will contain all the different 'verticals' from the database column - and filter the table based on the selection of the vertical)
I have the following front-end snippet called "client.php" that the client loads to get a report:
Client.php:
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="css/mediacallreport.css">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Generic Title</title>
</head>
<body>
<h2> Generic Reports </h2>
<h3>Report Formatting: </h3>
<div id="instruction">Select how you would like the data selected using the dropdowns below</div>
<!--DROPDOWNS-->
Vertical -
<select name="station" id="station">
<option value="all">All</option>
<script id="source" language="javascript" type="text/javascript">
$(function ()
{
$.ajax({
url: 'api.php', //the script to call to get data
data: "", //you can insert url argumnets here to pass to api.php
dataType: 'json', //data format
success: function(verticals) //on recieve of reply
{
for (var i in verticals)
{
var vertical = verticals[i];
var verticalID = verticals[0];
$('station').append("<option value=\""+verticalID+"\">"+verticalID+"</option>");
}
}
});
});
</script>
</select>
<!--TABLE BEGINNING - TABLE HEADER ROW-->
<table id="output">
<tr>
<th>ID</th>
<th>Station_Network</th>
<th>Vertical</th>
<th>Creative</th>
<th>Tolls</th>
<th>States</th>
<th>Date Range</th>
<th>Week</th>
<th>Ordered</th>
<th>Credits</th>
<th>Credits Totals</th>
<th>Not Used</th>
<th>Cleared</th>
<th>Total Uniques</th>
<th>Cleared Each Unique</th>
<th>Total Unique Connect</th>
<th>Cleared Each Unique Connect</th>
<th>Unique Connect 8am - 8pm</th>
<th>Cleared Unique 8am - 8pm</th>
<th>Calls over 10 Min</th>
<th>Calls over 10 Min %</th>
</tr>
<!--JAVASCRIPT TO GET INFORMATION FROM DB, ASSIGN VARIABLES AND PUT INTO TABLE ROWS-->
<script id="source" language="javascript" type="text/javascript">
$(function ()
{
//-----------------------------------------------------------------------
// 2) SEND HTTP REQUEST WITH AJAX
//-----------------------------------------------------------------------
$.ajax({
url: 'api.php', //the script to call to get data
data: "", //you can insert url argumnets here to pass to api.php
//for example "id=5&parent=6"
dataType: 'json', //data format
success: function(rows) //on recieve of reply
{
for (var i in rows)
{
var row = rows[i];
var id = row[0]; //get id
var station_network = row[1]; //get name
var vertical = row[2]; //get vertical
var creative = row[3]; //get creative
var tolls= row[4]; //get tolls
var states= row[5]; //get states
var date_range= row[6]; //get date_range
var week= row[7]; //get week
var ordered= row[8]; //get ordered
var credits= row[9]; //get credits
var credit_totals= row[10]; //get credit_totals
var not_used= row[11];
var cleared= row[12];
var total_uniques= row[13];
var cleared_each_unique= row[14];
var total_unique_connect= row[15];
var cleared_each_unique_connect= row[16];
var unique_connect_8am_to_8pm= row[17];
var cleared_each_8am_to_8pm= row[18];
var calls_over_10= row[19];
var calls_over_10_pct= row[20];
//--------------------------------------------------------------------
// DISPLAY THE CONTENT
//--------------------------------------------------------------------
//TABLES (ALTERNATING ROWS)
if (id % 2 == 0){
$('#output').append("<tr id=\"evenrow\"> <td>"+id+"</td><td>"+station_network+"</td><td>"+vertical+"</td><td>"+creative+"</td><td>"+tolls+"</td><td>"+states+"</td><td>"+date_range+"</td><td>"+week+"</td><td>"+ordered+"</td><td>"+credits+"</td><td>"+credit_totals+"</td><td>"+not_used+"</td><td>"+cleared+"</td><td>"+total_uniques+"</td><td>"+cleared_each_unique+"</td><td>"+total_unique_connect+"</td><td>"+cleared_each_unique_connect+"</td><td>"+unique_connect_8am_to_8pm+"</td><td>"+cleared_each_8am_to_8pm+"</td><td>"+calls_over_10+"</td><td>"+calls_over_10_pct+"</td></tr>");
} else {
$('#output').append("<tr id=\"oddrow\"> <td>"+id+"</td><td>"+station_network+"</td><td>"+vertical+"</td><td>"+creative+"</td><td>"+tolls+"</td><td>"+states+"</td><td>"+date_range+"</td><td>"+week+"</td><td>"+ordered+"</td><td>"+credits+"</td><td>"+credit_totals+"</td><td>"+not_used+"</td><td>"+cleared+"</td><td>"+total_uniques+"</td><td>"+cleared_each_unique+"</td><td>"+total_unique_connect+"</td><td>"+cleared_each_unique_connect+"</td><td>"+unique_connect_8am_to_8pm+"</td><td>"+cleared_each_8am_to_8pm+"</td><td>"+calls_over_10+"</td><td>"+calls_over_10_pct+"</td></tr>");
}
}
}
});
});
</script>
</body>
</html>
That talks to my api.php
api.php:
<?php
//--------------------------------------------------------------------------
// Connect to DB
//--------------------------------------------------------------------------
include 'DB.php';
$con = mysql_connect($host,$user,$pass) ;
$dbs = mysql_select_db($databaseName, $con);
//--------------------------------------------------------------------------
// 2) Query database for data
//--------------------------------------------------------------------------
//Rows of data in media-analysis
$result = mysql_query("SELECT * FROM $tableName"); //query
$data = array();
while ($row = mysql_fetch_row($result) )
{
$data[] = $row;
}
//Dropdown for Verticals
$verticalSql = "SELECT VERTICAL FROM media_analysis GROUP BY VERTICAL";
$verticalResult = mysql_query($verticalSql);
$verticalData = array();
while ($verticalRow = mysql_fetch_row($verticalResult)){
$verticalData[] = $verticalRow;
}
$finalarray = array ('rowdata' => $data, 'verticaldata' => $verticalData);
//--------------------------------------------------------------------------
// 3) echo result as json
//--------------------------------------------------------------------------
echo json_encode($finalarray);
?>
In Firebug I can see the data coming across and it looks something like this:
{"rowdata":[["1","canceled","canceled","canceled","canceled","canceled","03\/18\/2013-03-24\/2013","12","canceled","0","","","0.00","0","0.00","0","0.00","0","0.00","0","0.00"],["2","Station B","Vertical B","DEBIT","800-555-5555","CA","03\/18\/2013-03-24\/2013","12","$813.00","0","","","813.00","8","101.62","5","162.60","3","271.00","2","40.00"]],"verticaldata":[["canceled"],["Vertical B"]]}
Before I started including the 'dropdowns', I just had a simple json_encode ($data); and it would work fine and the table displayed exactly how I wanted it to. Since I've added another array to be passing, this is when things got crazy and I'm completely lost.
I know my coding is probably very poor, but I'm just trying to get a handle on this. All help appreciated.
The problem is that the code in your success handler expects an array to be returned:
success: function(verticals) //on recieve of reply
{
for (var i in verticals)
{
var vertical = verticals[i];
var verticalID = verticals[0];
$('station').append("<option value=\""+verticalID+"\">"+verticalID+"</option>");
}
}
However, as you showed in your example, verticals looks like this:
{"rowdata":[[...],[...]],"verticaldata":[["canceled"],["Vertical B"]]}
As you can see, verticals is an object, that contains two other objects (rowdata and verticaldata).
To make your current success handler work again, you first need to extract verticaldata from the AJAX response. Simply changing the code to this should work:
success: function(response) //on recieve of reply
{
var verticals = response.verticaldata;
for (var i in verticals)
{
var vertical = verticals[i];
var verticalID = verticals[0];
$('station').append("<option value=\""+verticalID+"\">"+verticalID+"</option>");
}
}
since you are using PHP and jQuery, you can use my library for that. Out-of-the-box dealing with any data that comes from PHP to Javascript, and vice-versa ;)
See here http://phery-php-ajax.net
in your case, it would be like this
<?php
include('Phery.php');
Phery::instance()->set(array(
'verticals' => function(data){
$r = new PheryResponse;
$verticalResult = mysql_query("SELECT VERTICAL FROM media_analysis GROUP BY VERTICAL");
$r->jquery('.station'); // Select it for subsequent chaining in the loop
$i = 0;
while ($verticalRow = mysql_fetch_row($verticalResult)){
$r->append('<option value="'.($i++).'">'.$verticalRow['VERTICAL'].'</option>'); // What is VERTICAL? Is that query the real one?
}
// every "append" call will happen to .station jquery selector automatically
return $r;
}
))->process();
?>
in your javascript code
$(function(){
phery.remote('verticals');
});
That's it. Why (re)generate data, when you can do it once in the server (where data generation belongs)
Of course, you could just return the JSON and use phery:json, but that's not practical in your case
return PheryResponse::factory()->json($verticalData);
And the Javascript side
phery.remote('verticals', null, null, false).on('phery:json', function(data){
for (var i in data){
// do your append here
}
});

PHP MySQL Google Chart JSON - Complete Example [closed]

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>

Passing PHP array into Javascript through JSON to update Google Chart

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>
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.
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);
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
?>

Categories