I'm curious if I can inject PHP code to the datatable of google visualization instead of using JSON strings.
<html>
<head>
<!--Load the AJAX API-->
<script type="text/javascript" src="https://www.google.com/jsapi"></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', 'Topping');
data.addColumn('number', 'Slices');
data.addRows(
<?php
some PHP code that echoes the same format like this
[['Mushrooms', 3],['Onions', 1],['Olives', 1],['Zucchini', 1],['Pepperoni', 2]]
?>);
// Set chart options
var options = {'title':'How Much Pizza I Ate Last Night',
'width':400,
'height':300};
// Instantiate and draw our chart, passing in some options.
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>
I'm trying to make events on google visualization. Any help/suggestions is very much appreciated. Thanks!
#scibuff has the right idea.
$my_array = array(
array('Mushrooms',3),
array('Onions',1),
array('Olives',1),
array('Zucchini',1),
array('Pepperoni',2)
);
echo json_encode( $my_array );
will give you [["Mushrooms",3],["Onions",1],["Olives",1],["Zucchini",1],["Pepperoni",2]]
Related
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>
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 am trying to produce a chart using Google visualization and php/mysql.
My data looks like this:
['RTI', 3],
['USAID', 1],
['Task Force', 1],
['DFID', 1],
['Other', 2]
If I print $jdata I get:
[{"Response":"Other","Count":"3"},{"Response":"RTI","Count":"3"},{"Response":"USAID","Count":"4"}]
which looks pretty close. Any advice?
<script type="text/javascript" src="https://www.google.com/jsapi"></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(<?php $jdata ?>);
// Set chart options
var options = {'title':"Question1: I'm here to represent:",
'width':400,
'height':300};
// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.PieChart(document.getElementById('chart_div1'));
chart.draw(data, options);
}
</script>
<?php $jdata ?> does nothing - you need to echo it - <?php echo $jdata ?>!
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.
I've got a problem with the visualization of data with google's charts api after an ajax call.
First I made an ajax call and fetched a json object. After that I want to extract some data out of the json and draw a gauge chart. Getting the json and extracting the data works fine, but when I try to load the chart, the body gets removed and I get a blank/white screen. Does anyone knows what I am doing wrong? I also tried to hard code values for the chart instead of taking the json values (but kept the ajax call before loading the chart), but it didn't work neither.
function loadStats(){
var http = getRequestObject();
var city = "berlin";
http.open("GET", "getTwitterSentiments.php?city="+city, true);
http.onreadystatechange=function() {
getStatistic(http)
};
http.send(null);
}
function getStatistic(request) {
if ((request.readyState == 4) && (request.status == 200)) {
var data = request.responseText;
var JSONStats = eval("(" + data + ")");
loadGauge(JSONStats.sentiment_index);
}
function loadGauge(sentiment){
google.load('visualization', '1', {packages:['gauge']});
google.setOnLoadCallback(drawGauge);
function drawGauge() {
var data = google.visualization.arrayToDataTable([
['Label', 'Value'],
['Test', sentiment]
]);
var options = {
width: 100,
height: 100,
redFrom: 0,
redTo: 45,
yellowFrom: 45,
yellowTo: 55,
greenFrom: 55,
greenTo: 100,
minorTicks: 10
};
var chart = new google.visualization.Gauge(document.getElementById('testgchart'));
chart.draw(data, options);
}
}
Try using the callback feature of google.load() function.
For instance, for your code, try the following:
function loadGauge(sentiment){
google.load('visualization', '1.0', {'packages':['gauge'], 'callback': drawGauge});
}
function drawGauge(){
...
chart.draw(data, options);
}
For more information, check the 'Dynamic loading' section of Google Loader Developer Guide:
https://developers.google.com/loader/#Dynamic
If i understand correctly, calling loadGauge() multiple times will not cause multiple trips to Google servers to load the required APIs, but just once.
I guess your element testgchart is not load in the DOM yet, your code should work.
I made an example from your code :
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script src="https://www.google.com/jsapi"></script>
<script>
function loadGauge(val){
google.load('visualization', '1', {packages:['gauge']});
google.setOnLoadCallback(drawGauge);
function drawGauge() {
var data = google.visualization.arrayToDataTable([
['Label', 'Value'],
['Test', val],
]);
var options = {
width: 100,
height: 100,
redFrom: 0,
redTo: 45,
yellowFrom: 45,
yellowTo: 55,
greenFrom: 55,
greenTo: 100,
minorTicks: 10
};
var chart = new google.visualization.Gauge(document.getElementById('average'));
chart.draw(data, options);
}
}
</script>
</head>
<body>
<div id="average"></div>
<script>loadGauge(99)</script>
</body>
</html>
But it doesn't work if you delete this line <script>loadGauge(99)</script> and replace the body tag with <body onload="loadGauge(99)">. Your probably doing something similar.
If your sure the element testgchart is present then put a log in loadGauge and tell me if it really get called by getStatistic.