google charts api - pie chart is not displaying - php

I am trying to create a piechart dynamically by using Google Chart api. i am taking values from the database. I am not getting how exactly this can be done.
$resultViewed = $this->model_report_product->getMostViewed();
$stringResult ="var data= google.visualization.arrayToDataTable([ ['Product', 'Views'],";
foreach($resultViewed as $results)
{
$stringResult = $stringResult . "['".$results['name']."',".$results['quantity']."],";
break;
}
$stringResult .= "]);";
$this->data['Viewed'] = $stringResult;
When i run this, it gives Chart heading but pie chart is not displayed but it says No Data.

You can't pass a variable in memory between php to html. You have to print it out to pass it to html. So where you have:
return $stringResult;
you should print it out like:
print $stringResult;

Related

Multiple graphs in php loop

I have a problem with google charts. I developed a web page with 5 (generated with php) and 5 ID for each :
echo "<div id = \"ID\" style=\"display:none;\">"
I also have 5 json arrays with all the information. I show in each the data in a table but I would like also show a graph with my data.
I tried to do in this way (but it doesn't work):
for ($i = 0; $i<$n;$i++){
$jsonTable = json_encode(${'table'.$Result_array[$i][1]});
$ID = $Result_array[$i][1]; //ID for the div
echo "<script type=\"text/javascript\">
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: 'Company Performance',
hAxis: {title: 'L value', titleTextStyle: {color: 'red'}, gridlines:{count:10} },
vAxis: {
title: \"I rms\",
maxValue:1.5,
gridlines:{count:10}
}
};
// Instantiate and draw our chart, passing in some options.
// Do not forget to check your div ID
var chart = new google.visualization.ColumnChart(document.getElementById('".$ID."'));
chart.draw(data, options);
}
}
</script>";
}
If I use this code only for 1 table, works fine, but when I use a loop and try to generate multiple graphs, it doesn't work.
Anyone could help me? thanks!
P.S: Maybe I also have to explain that, first of all, I have a table with my 5 results, and when I click, I have a onclik function to unhide the appropiate . This works always (with graphs and without it) but never display the graphs....
Where are the 5 ids you are looping through only one id
var chart = new google.visualization.ColumnChart(document.getElementById('".$ID."'));
It should be like this
var chart = new google.visualization.ColumnChart(document.getElementById('".$ID."_".$i"'));
and add the div like
echo "<div id = \"ID_0\" style=\"display:none;\">"
echo "<div id = \"ID_1\" style=\"display:none;\">"
echo "<div id = \"ID_2\" style=\"display:none;\">"
echo "<div id = \"ID_3\" style=\"display:none;\">"
echo "<div id = \"ID_4\" style=\"display:none;\">"

How to load dynamic data into google pie chart?

I am using an ajax function to get data for rendering Google Pie chart and loading those data in javascript but some how the Pie chart is not rendering but when i hard code the AJAX output into javascript pie chart function it does render perfectly. Below is my code can any one tell me what's wrong? thank you for your help.
<?php
$sales_data = koolajax.callback(get_asin_repo($asin,$sku));
?>
JS here:
// AJAX Output is ['POS', 'Sold This Month'],['AZN CG UK',893],['AZN JT UK',449],['AZN PT UK',1349]
alert($sales_data);
//var data = google.visualization.arrayToDataTable([$sales_data]);//This doesn't work
//This Works
var data = google.visualization.arrayToDataTable([['POS', 'Sold This Month'],['AZN CG UK',893],['AZN JT UK',449],['AZN PT UK',1349]]);
var options = {
title: 'Statistics For '+$asin
};
var chart = new google.visualization.PieChart(document.getElementById('chart_div1'));
chart.draw(data, options);
it Was really simple. all i need to do was get data from DB in JSON format and pass it in
var data = new google.visualization.DataTable($sales_data);
function instead of
var data = google.visualization.arrayToDataTable([$sales_data])
And it works.
Thank you all for your support and time...........
You must check the kind of variable returned from server and pack it in way that GoogleChart understands.
In your case, you requested that google.visualization.arrayToDataTable to create a DataSource instance for you. But that static method also requires that YOU follow this rule:
This method takes in a 2-dimensional array and converts it to a
DataTable. See the
Google Charts Documentation
So make a check before calling that routine.
if ( $sales_data instanceof Array )
{
var willWork = [];
var entry;
while ( $sales_data.length )
{
entry = $sales_data.shift();
if ( !(entry instanceof Array) || entry.length < 2 )
window.alert( 'Incorrect server return. Call support.' );
willWork.push( entry );
}
}
else
window.alert( 'Incorrect server return. Call support.' );
Google pie chart get data from PHP
I have been searching since 4 hours how to populate data from PHP to google pie chart but not found any solution, actually, my data format was wrong in PHP.
You can prepare data in PHP using this way:
function yourFunction(){
$data = array();
$data[0] = array("Status", "Revenue");
$data[1] = array('Pending', 500);
$data[2] = array('Confirmed', 1000);
$data[3] = array('Payable', 3000);
return json_encode($data );
}
Parse data on frontend:
var obj = JSON.parse(data);
var data = new google.visualization.arrayToDataTable(data);

Google Chart integration with PHP & MySQl

I'm trying to create a sample bar chart or pie chart from a MySQL data that I have. I know how to use Google Charts and its basic functionality. The question is..How can I integrate my PHP/MySQL data to create a sample Bar or Pie Chart.
I have the simplest data to display: Count of Apples, Banana and Orange.
I can only display them using the basic coding from Google Charts( putting the values in the Google chart codes),but I need to query them from MySQL. Do I need json for this?
Thanks!
A simple example, get the data from your database and pass it into charts, like:
while($r = mysql_fetch_assoc($query)) {
$google_JSON = "{cols: [";
$column = array_keys($r);
foreach($column as $key=>$value){
$google_JSON_cols[]="{id: '".$key."', label: '".$value."'}";
}
$google_JSON .= implode(",",$google_JSON_cols)."],rows: [";
$google_JSON_rows[] = "{c:[{v: '".$r['id']."'}, {v: ".$r['count']."}]}";
}
// you may need to change the above into a function that loops through rows, with $r['id'] etc, referring to the fields you want to inject..
//pass it into google charts data
echo $google_JSON.implode(",",$google_JSON_rows)."]}";

Creating jqplot graph in php page

Im trying to learn php by doing a little project using apache server. I have a php page where I want to display a bar chart with jqplot using data i pull from a MySql query. I already have a query working giving me the data i want. The problem is i dont know how to implement this into a jqplot graph. Im guessing i need to make an ajax call but if i can avoid that i would like to. my php page code so far is here http://snipt.org/oknnl2.
the javascript for the bar chart is here http://snipt.org/oknoi3.
i want the chart to render in div id=chartdiv thats on line 177. I have to visualize like 6 charts. if i can get some help on doing this one, im sure i can use the same process to build the others.
PHP cannot create the javascript plot and send it downstream to the client, but you don't have to make an actual AJAX call after the page is loaded either. Simple javascript once the page loads will suffice. If you retrieve the data you need at the PHP level, you can then make it available to javascript in the HTML received by the client. The steps to make this happen:
First, use PHP to retrieve the data you need from the MySQL database.
Then, output the plot data you retrieved using PHP inside a javascript
code block as part of the HTML that PHP sends to the client.
Execute the javascript with the data seeded by PHP on page load.
So, a simplified example:
<?php
// Retrieve plot data from mysql
$q = '...';
$r = mysql_query($q);
$plot_row1 = array();
$plot_row2 = array();
$plot_row3 = array();
while ($row = mysql_fetch_array($r)) {
// append values to $plot_row1, $plot_row2 and $plot_row3 arrays
}
$my_page_title = 'My first PHP/JS Combo Foray';
?>
<html>
<head>
<script type="text/javascript" src="/scripts/jquery-1.5.2.min.js"></script>
<script type="text/javascript" src="/scripts/my_plotter.js"></script>
</head>
<body>
<h1><?php echo $my_page_title; ?></h1>
<div id="chartdiv">
Hold on, javascript is loading the plot ...
</div>
</body>
</html>
<script type="text/javascript">
$(document).ready(function() {
// we're combining the php array elements into a comma separated list
// so that when the code is output javascript thinks it's an array.
// if the $plot_row1 = array(1, 2, 3) then we'd get this:
//
// row1 = [1, 2, 3];
//
// if you needed quotes around the imploded php array values (if they
// are strings where javascript is concerned) you could do this instead:
//
// row1 = ["<?php echo substr(implode('","', $plot_row1), 0, -2); ?>"];
row1 = [ <?php echo rtrim(implode(',', $plot_row1), ','); ?> ];
row2 = [ <?php echo rtrim(implode(',', $plot_row2), ','); ?> ];
row3 = [ <?php echo rtrim(implode(',', $plot_row3), ','); ?> ];
// call your js function that creates the plot
showBrittleness(row1,row2,row3);
// add whatever js code you need to append the plot to $('#chartdiv')
}
</script>
UPDATE
According to a cursory examination of the jqplot docs, if you edit line 12 of the javascript you link from this:
var plot1 = $.jqplot('chart1', [s1, s2], {
To this:
var plot1 = $.jqplot('chartdiv', [s1, s2], {
Your function should render the plot in the 'chartdiv' id element. It seems the first argument to the $.jqplot function is the element in which to create it ...

Putting mysql stored points on a google map

I have a MySQL database with a table full of geographic points, latitudes and longitudes. I want these coordinates displayed on a Google map as points. Is it possible for JavaScript to directly access the database or would I need to do that first using PHP?
Yes, it's possible and you'd have to use PHP to retrieve your points from the database. For examples of the Google part of your request, have a look at the Google Maps Javascript API V3 reference and update your question when you've put some code together.
You would need some sort of server side language to be involved. Likely ajax/json request or pulling an XML file and looping through the data. If you're more comfortable with PHP you would loop through your results within a script tag:
<script type="text/javascript">
var mapArray = new Array;
<?php
$i = 0;
$result = mysql_query('SELECT * FROM location');
while ($row = mysql_fetch_assoc($result)) {
echo 'mapArray[' .$i++ . '] = new Array(' . $row['lat'] . ',
' . $row['lng'] . '");
';
}
?>
for (var i in mapArray) {
var myLatLng = new GLatLng(mapArray[i][0], mapArray[i][1]);
GMarker(myLatLng);
}
</script>
It is possible to use a PHP script as a link between JavaScript and the SQL database witht he use of the JavaScript XMLHttpRequest object.

Categories