PHP array into google charts - php

I need a little help putting PHP data into google charts.
I have created a simple array
$chart_arr = array($year, $new_balance);
json_encode($chart_arr);
If I run
<?php echo json_encode($chart_arr);?>
I see the following: [2015,1150] [2016,1304.5] [2017,1463.635] [2018,1627.54405] [2019,1796.3703715], so I think (?) I am getting the right numbers encoded from my forloop that generates $year and $new_balance.
I want to chart these numbers in google chart
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Year');
data.addColumn('number', 'Balance');
data.addRows([
<?php echo json_encode($chart_arr);?>
]);
Or alternatively:
data.addRows([
<?php echo $chart_arr;?>
]);
And then continues...
var options = {
title: 'My Savings',
curveType: 'function',
legend: { position: 'bottom' }
};
var chart = new google.visualization.LineChart(document.getElementById('curve_chart'));
chart.draw(data, options);
}
displaying as...
<div class="grid-container">
<div class="grid-100 grid-parent">
<div id="curve_chart" style="width: 100%; height: auto"></div>
</div>
</div>
I have tried a number of variations but am either not getting the data into the chart or not getting a chart to display.
Could someone help me to show where I am going wrong?
I saw another related post that used the following code:
$chartsdata[$i] = array($testTime, $testNb);
echo json_encode($chartsdata);
var jsonData = $.ajax({
url: "test.php",
dataType: "json",
async: false
}).responseText;
var obj = JSON.stringify(jsonData);
data.addRows(obj);
Is this the approach I need to be looking at?
Thanks in advance

i see you haven't found out how to do it after your first question, so i've made you a working example here, hope this helps you Dave :).
If you've got some questions about this, feel free to ask!
<?php
//create array variable
$values = [];
//pushing some variables to the array so we can output something in this example.
array_push($values, array("year" => "2013", "newbalance" => "50"));
array_push($values, array("year" => "2014", "newbalance" => "90"));
array_push($values, array("year" => "2015", "newbalance" => "120"));
//counting the length of the array
$countArrayLength = count($values);
?>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Year');
data.addColumn('number', 'Balance');
data.addRows([
<?php
for($i=0;$i<$countArrayLength;$i++){
echo "['" . $values[$i]['year'] . "'," . $values[$i]['newbalance'] . "],";
}
?>
]);
var options = {
title: 'My Savings',
curveType: 'function',
legend: { position: 'bottom' }
};
var chart = new google.visualization.LineChart(document.getElementById('curve_chart'));
chart.draw(data, options);
}
</script>
<div class="grid-container">
<div class="grid-100 grid-parent">
<div id="curve_chart" style="width: 100%; height: auto"></div>
</div>
</div>

I have dealt quite a bit with the Google Charts API recently and I have a few recommendations. The PHP code that you have written should largely work, but it does require that your Javascript code be embedded in a PHP page.
Maybe that is okay for your purposes, but I mostly recommend keeping your Javascript separate from your PHP. Some developers may be comfortable with one, but not the other, so mixing the two languages could become a maintenance issue. Now, that pretty much leaves you with using AJAX to retrieve your JSON charts data. This is a good approach, but I do not like the code that you featured in your question for a few reasons.
Firstly, the code uses async: false which will remove your user's control of the browser while the data is being fetched. In other words, the browser will appear to freeze until the data is returned from the AJAX request.
Also, I do not understand the whole .responseText convention. I understand what the code is accomplishing; I just fail to understand why the author chose that particular approach. Here is what I would do instead.
$.ajax({
url: "test.php",
dataType: "JSON",
data: [any POST parameters that you need here],
type: "POST",
success: function(json) {
var jsonData = JSON.parse(json); // jsonData will be a Javascript object or array.
data.addRows(jsonData);
drawChart();
},
error: function(jxqhr) {
// Handle a bad AJAX call
}
});
So how does this help your application overall? Well, in your server side code, you can handle any errors (i.e. bad user input) by responding to the AJAX call with a HTTP 500 error and the AJAX call can communicate the problem to your user. Furthermore, when your page loads, the rest of the page will continue loading while your AJAX call is off fetching data.
JS Fiddle

json_encode works just fine, you can put it in a variable like var grafica = <?php echo json_encode($grafica); ?> ; (look my example below) or just like you put it in your example, except that the only problem in it, is that you have double brackets, the ones inside jaso_encode($chart_arr) object and the externals data.addRows([ ... ]), that gives you [[...]] and generates and error, take off the brackets, try it like this:
data.addRows(
<?php echo json_encode($chart_arr);?>
);
and not this
data.addRows([
<?php echo json_encode($chart_arr);?>
]);
I have included and example of how I am using it, be aware that in the documentation, (which in my opinion could be better) they placed the entire code in the <head> section because they have all the data there, but that may cause problems in real working examples, I only placed the CDN (Content Delivery Network) of google chart in the <head> and in the <body> all the Javascript code after the PHP code, not included in this example for clarity purposes, then the <div> but this last could go before the script tags. The order is important because you need to get the data first before constructing the graph.
I hope this helps.
<!DOCTYPE html>
<head>
<meta charset="utf-8"/>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
</head>
<body>
<script type="text/javascript">
google.charts.load("current", {packages:["corechart"]});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn('string', 'fecha'); // Implicit domain column.
data.addColumn('number', 'peso'); // Implicit data column.
data.addColumn({type:'string', role:'annotation'}); // columna para anotaciones
data.addColumn({type:'string', role:'style'}); // comumna para estilo
var grafica = <?php echo json_encode($grafica); ?> ;
data.addRows(grafica);
var options = {
title:'Peso Total', width:600,height:400,
colors: ['#C0C0C0'],
curveType: 'function',
legend: 'none',
pointSize: 12,
annotations: {
textStyle: {
fontName: 'Times-Roman',
fontSize: 32,
color: '#99ff99',
opacity: 0.5,
}
}
};
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
<div id="chart_div" style="margin: 80px auto; width: 650px; height: 450px; border: 2px solid #4CAF50; border-radius: 20px; padding:5px; "></div>
</html>

Related

how to show a graph in each row in usgin googlechart(or chart.js etc)

I've been trying to display a graph in each row inside one page using Google chart but
I have no idea how to do that.
I get data from database when making a graph.
putting aside if this code below is right, here's my image.
#foreach ($titles as $title)
{{$title->title_name}}
<?php $getData = App\Graph::getNumber($title->id)?>
<div id="graph_bar{{$title->id}}" ></div> ←graph
#endforeach
<script type="text/javascript">
var barA= #json($getData->numberA);
var barB = #json($getData->numberB);
var barC= #json($getData->numberC);
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawchart);
function drawchart() {
var data = google.visualization.arrayToDataTable([
['', '', '', ''],
['', barA, barB , barC],
]);
var options = {
isStacked: true,
isStacked:'percent',
legend: {position: 'none'},
series: {
0:{color:'red'},
1:{color:'blue'},
2:{color:'grey'},
}
};
var chart = new google.visualization.BarChart(document.getElementById('graph_bar'));
chart.draw(data, options);
}
$(window).resize(function(){
drawchart();
});
</script>
1.Is it possible to do that(display a graph in each row) in the first place?
2.I'd like to get ID from HTML at javascript.
if anyone knows anything about this, I'd appreciate if if you would help me out.
thank you.

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

Google charts api after ajax call

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.

google charts as a javascript function

forgive my javascript.. I want to take the google charts code and use it once as a function then call it in the page loop with a single line as follows:
javascript function (in header)
var taxes, purchase_costs, closing_costs, holding_costs, cost_money, commissions, theid;
function costPieChart(taxes,purchase_costs,closing_costs,holding_costs,cost_money,commissions,theid)
{
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Item');
data.addColumn('number', 'Cost');
data.addRows([
['Taxes', taxes],
['Purchase Costs', purchase_costs],
['Closing Costs', closing_costs],
['Holding Costs', holding_costs],
['Cost of Money', cost_money],
['Commissions', commissions]
]);
var options = {
width: 190, legend: 'none',
colors:['red','blue', '993399', 'grey', 'ff6600', 'green']
};
var chart = new google.visualization.PieChart(document.getElementById(theid));
chart.draw(data, options);
}
}
then in the html by php loop
<script type="text/javascript">
costPieChart(<?php echo round($method['tax_amount_for_days']).', '.round($method['closing_costs_purchase']).', '.
round($method['holding_costs']).', '.round($method['cost_of_money']).', '.round($method['commissions_amount']).", 'chart_div".$i."'" ; ?>);
</script>
<div class="chart_wrap"> <div id="chart_div<? echo $i ?>"></div> </div>
The loop works renders the javascript and html but alas, the cute lil pie chart is absent. Help?
You never call your drawChart function. You need to call that at some point to draw your pie chart.
var options = {
width: 190, legend: 'none',
colors:['red','blue', '993399', 'grey', 'ff6600', 'green']
};
var chart = new google.visualization.PieChart(document.getElementById(theid));
chart.draw(data, options);
drawChart(); // <--- like this
}

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