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.
Related
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.
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>
I need some help. I have some info in my db that I want to show in 2 charts using Google charts script.
Both scripts works but not when I use both scripts in a same page.. I bet is a problem with the while that are both equals since I need to show the same info. If I delete the first while the second loop start to work, but if no, the first just work.
The app works well because if I hardcode the values by hand and without the while works well both..
Here's the code:
<!-- First Chart start here: -->
<script type="text/javascript">
google.load("visualization", "1", {
packages: ["corechart"]
});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Formato', 'Cantidad'], <? php
//da problema si hay 2 while
while ($DatRDV = mysql_fetch_array($nrollos)) {
echo "['".$DatRDV['Formato'].
"',".$DatRDV['nRollos'].
"],";
} ?> ]);
var options = {
title: 'Formato de Rollos'
};
var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
<!-- Second chart start here: -->
<script type="text/javascript">
function drawVisualization() {
// Create and populate the data table.
var JSONObject = {
cols: [{
id: 'format',
label: 'Formato',
type: 'string'
}, {
id: 'cantidad',
label: 'Cantidades',
type: 'number'
}],
rows: [
<? php
while ($DatRDV = mysql_fetch_array($nrollos)) {
echo "{c:[{v: '".$DatRDV['Formato'].
"'}, {v: ".$DatRDV['nRollos'].
"}]},";
} ?> ]
};
var data = new google.visualization.DataTable(JSONObject, 0.5);
// Create and draw the visualization.
visualization = new google.visualization.Table(document.getElementById('table'));
visualization.draw(data, {
'allowHtml': true
});
}
google.setOnLoadCallback(drawVisualization);
</script>
try;
mysql_data_seek($nrollos,0);
before the 2nd loop
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.
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
}