Style is not showing in Google org chart - php

$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.

Related

Google.visualization.dashboard not rendering with json array php

I’m passing an encoded json array from a MYSQL query to render a google.visualization.dashboard. I am almost certain the problem is with my array but I can't find where. The code works when I draw the chart google charts directly (eg google.visualization.PieChart) but not when I use dashboard / control wrapper / chart wrapper classes.
That leads me to believe that the problem is either with my array structure or that google.visualization.dashboard requires the data table to be populated differently than the charts.
PHP code (loadpiechart.php):
$table['cols'] = array(
array('label' => 'NZ Crime', 'type' => 'string'),
array('label' => 'Value', 'type' => 'number'),
);
$rows=array();
while($r=mysqli_fetch_assoc($res)){
$temp=array();
$temp[]=array('v'=> $r['Offence']);
$temp[]=array('v' => $r['Total']);
$rows[]=array('c' => $temp);
}
$table['rows'] = $rows;
$jsonTable = json_encode($table, JSON_NUMERIC_CHECK);
echo $jsonTable;
Which gives me the following array[]
{"cols":[{"id":"A","label":"NZ Crime","type":"string"},{"id":"B","label":"Value","type":"number"}],"rows":[{"c":[{"v":" Acts intended to cause injury"},{"v":97}]},{"c":[{"v":" Sexual assault and related offences"},{"v":44515}]},{"c":[{"v":" Dangerous or negligent acts endangering persons"},{"v":3016}]},{"c":[{"v":" Abduction, harassment and other related offences against a person"},{"v":859}]},{"c":[{"v":" Robbery, extortion and related offences"},{"v":14157}]},{"c":[{"v":" Unlawful entry with intent\/burglary, break and enter"},{"v":2641}]},{"c":[{"v":" Theft and related offences"},{"v":59323}]},{"c":[{"v":" Fraud, deception and related offences"},{"v":136932}]},{"c":[{"v":" Illicit drug offences"},{"v":9726}]},{"c":[{"v":" Prohibited and regulated weapons and explosives offences"},{"v":22994}]},{"c":[{"v":" Property damage and environmental pollution"},{"v":7074}]},{"c":[{"v":" Public order offences"},{"v":58483}]},{"c":[{"v":" Offences against justice procedures, government security and government operations"},{"v":46105}]},{"c":[{"v":" Miscellaneous offences"},{"v":19084}]}]}
And finally the HTML code.
html>
<head>
<!--Load the AJAX API-->
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
// Load the Visualization API and the piechart package.
google.charts.load('current', {packages:['corechart', 'table', 'controls']});
// Set a callback to run when the Google Visualization API is loaded.
google.setOnLoadCallback(drawTable);
function drawTable() {
var jsonData = $.ajax({
url: "loadpiechart.php",
dataType:"json",
async: false
}).responseText;
// Create our data table out of JSON data loaded from server.
var data = new google.visualization.DataTable(jsonData);
var table = new google.visualization.ChartWrapper({
'chartType': 'Table',
'containerId': 'table_div',
});
var chart = new google.visualization.ChartWrapper({
'chartType': 'PieChart',
'containerId': 'chart_div',
'view': {'columns': [0, 1]},
});
var control = new google.visualization.ControlWrapper({
'controlType': 'CategoryFilter',
'containerId': 'control_div',
'options': {
'filterColumnIndex': 0,
}
});
var dashboard = new google.visualization.Dashboard(
document.getElementById('dashboard_div'));
dashboard.bind([control], [table,chart]);
dashboard.draw(data);
}
</script>
</head>
<body>
<div id="dashboard_div" style="border: 1px solid #ccc; margin-top: 1em">
<p style="padding-left: 1em"><strong>NZ Crime Stats</strong></p>
<table class="columns">
<tr>
<td>
<div id="control_div" style="padding-left: 15px"></div>
</td>
</tr><tr>
<td>
<div id="chart_div" style="padding-top: 15px"></div>
</td><td>
<div id="table_div" style="padding-top: 30px"></div>
</td>
</tr>
</table>
</div>
</body>
</html>
I would recommend to change the AJAX call to a non-blocking asynchronous call and call the drawing routine in the success() method:
function drawTable() {
$.ajax("https://gist.githubusercontent.com/Moonbird-IT/da4c7d76a69eb250478bb55b5d2360f5/raw/9dbf9d92981a3c9b71906dd3a680a2cdeca7c4aa/googlecharts.json", {
dataType: "json",
success: function(jsonData) {
// Create our data table out of JSON data loaded from server.
var data = new google.visualization.DataTable(jsonData);
...
}
});
}
I updated your code to use the changed recommendation, here is a working Fiddle of it.
My problem was that I wasn't calling jQuery. I added this line of code and it works my original code plus this addition.
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
Link here for google.visaulization documentation https://developers.google.com/chart/interactive/docs/php_example

how can i transform my josn_encode data in array into google bar chart?

This is my json_encoded data
$encoded_data = json_encode($data);
echo $encoded_data;
[{"cols":"2017-09-02 11:01:55","rows":"1186.55"},{"cols":"2017-09-03 11:31:35","rows":"1311.45"},{"cols":"2017-09-06 15:22:38","rows":"90000.00"},{"cols":"2017-09-06 16:39:16","rows":"90000.00"},{"cols":"2017-09-06 16:40:09","rows":"630.00"},{"cols":"2017-09-06 17:25:26","rows":"1311.45"},{"cols":"2017-09-06 17:54:50","rows":"1311.45"},{"cols":"2017-09-07 09:28:57","rows":"1311.45"},{"cols":"2017-09-07 10:20:16","rows":"1575.00"},{"cols":"2017-09-07 10:22:28","rows":"1311.45"},{"cols":"2017-09-07 10:27:52","rows":"1311.45"},{"cols":"2017-09-07 10:34:00","rows":"1311.45"},{"cols":"2017-09-07 10:39:46","rows":"91575.00"},{"cols":"2017-09-07 10:40:48","rows":"91311.45"},{"cols":"2017-09-07 10:47:34","rows":"1575.00"},{"cols":"2017-09-07 10:50:53","rows":"1575.00"},{"cols":"2017-09-07 10:51:18","rows":"1575.00"}]
<!--Load the AJAX API-->
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
// Load the Visualization API and the corechart package.
google.charts.load('visualization', '1', {'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.
var jsonData = <?php echo $encoded_data; ?>
var data = new google.visualization.DataTable(jsonData);
// Set chart options
var options = {'title':'sales chart',
'width':400,
'height':300};
// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.BarChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
<!--Div that will hold the pie chart-->
<div id="chart_div"></div>
It gives me an error the table has no columns.
the json is not in the correct format to create the data table directly,
see the structure of the JavaScript literal object described here...
if you don't want to change the format, then it can be transformed using javascript
see following working snippet...
google.charts.load('current', {
callback: drawChart,
packages: ['corechart']
});
function drawChart() {
var jsonData = [{"cols":"2017-09-02 11:01:55","rows":"1186.55"},{"cols":"2017-09-03 11:31:35","rows":"1311.45"},{"cols":"2017-09-06 15:22:38","rows":"90000.00"},{"cols":"2017-09-06 16:39:16","rows":"90000.00"},{"cols":"2017-09-06 16:40:09","rows":"630.00"},{"cols":"2017-09-06 17:25:26","rows":"1311.45"},{"cols":"2017-09-06 17:54:50","rows":"1311.45"},{"cols":"2017-09-07 09:28:57","rows":"1311.45"},{"cols":"2017-09-07 10:20:16","rows":"1575.00"},{"cols":"2017-09-07 10:22:28","rows":"1311.45"},{"cols":"2017-09-07 10:27:52","rows":"1311.45"},{"cols":"2017-09-07 10:34:00","rows":"1311.45"},{"cols":"2017-09-07 10:39:46","rows":"91575.00"},{"cols":"2017-09-07 10:40:48","rows":"91311.45"},{"cols":"2017-09-07 10:47:34","rows":"1575.00"},{"cols":"2017-09-07 10:50:53","rows":"1575.00"},{"cols":"2017-09-07 10:51:18","rows":"1575.00"}];
var data = new google.visualization.DataTable();
data.addColumn('string', 'x');
data.addColumn('number', 'y');
jsonData.forEach(function (row) {
data.addRow([
row.cols,
parseFloat(row.rows)
]);
});
var options = {
title: 'sales chart',
width: 400,
height: 300,
chartArea: {
left: 140
}
};
var chart = new google.visualization.BarChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>

Display a google chart with json & 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.

How to create Google API line chart using PHP array / JSON?

I'm trying to create a simple Google line chart using their API. Hard coded, this works:
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Year', 'Sales'],
['2010', 1000.31],
['2011', 1170.68],
['2012', 660]
]);
var options = {
};
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
However, I am trying to populate the chart values using data from MySQL. How do I get this to work?
$arr = array('Year' => 'Sales', '2010' => 1000.31, '2011' => 1170.68, '2012' => 660);
$chart_data = json_encode($arr);
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.DataTable(<?php echo $chart_data ?>);
var options = {
};
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
Basically, I am creating a PHP array from a MySQL result and trying to display its contents in the Google chart.
I know this is an old post but for anyone else who finds it I just wanted to post this which is the obvious answer:
https://developers.google.com/chart/interactive/docs/php_example
HTML:
<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() {
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>
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
?>
Sample data:
{
"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}]}
]
}
To use a database, you would simply have to generate an array of columns and an array of rows and then json_encode them and return that instead of the .json file via PHP.
You can use the below link code and its in php and gd library and very simple to integrate with application.
http://www.kidslovepc.com/php-tutorial/php-dynamic-chart-plot.php.

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