How to load dynamic data into google pie chart? - php

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);

Related

Get response array from jquery ajax to php

I am trying to populate a table from mysql based on a select box option using jquery ajax, so far this is my jquery code. I can show the result on the alert box but i dont know how to send it to php so that i can loop thru the array and create the table.
// selector de campaña en reporte de clientes mas activos
$(document).ready(function(){
$('.selector-camp').change(function(){
var campaing = $('.selector-camp').val();
$.post( "../campanas/test", { 'camp': campaing },
function( data ) {
alert( data.result );
}, "json");
});
});
As I use JavaScript more than jquery, I'll write it in JavaScript and I am sure you can do that in Jquery too, but in JavaScript it's also easy to do
function( data )
{
createTable(data.result); //pass your json array to JS function
}, "json");
//here i create js function
function createTable(array)
{
var array = JSON.parse(array); //decoding from json format
//So if i have numbers in array like [1, 2, 3, 4] and want
//to create row with them something like this should be done
var table = document.createElement("table"); //create table
var tr = document.createElement("tr"); //create row
for(var i=0; i<array.length; i++)
{
var td = document.createElement("td");
td.innerHTML = array[i];
tr.appendChild(td);
//for each array element creates cell and appends to row
}
table.appendChild(tr);
//Then you can have some empty div and append table to it
var div = //your empty div
div.appendChild(table);
}
Please check below php prototype code as per your requirement.
From ajax please make a call to this file it will return you a json response since I have used json_encode() function, you can directly return array as well but I would not suggest that, also you can edit this code for further mysql query.
<?php
test();
function test(){
$camp = htmlspecialchars($_POST['camp']);
isset($camp)&&!empty($camp)?
$data = array('test_key'=>'test_value');
echo json_encode($data);
}
?>

jqplot to retrieve results from php-mysql

I am having problems plotting my pie chart using jqplot.
After getting my results from php i have converted it to json using json_encode. The output is
{"a":2,"b":1,"c":5,"d":650}
Now when i try to put these results into my javascript
<script class="code" type="text/javascript">
$(document).ready(function(){
// method 1
//var data1 = document.getElementById("dataArray").value;
//eval('data1 = '+data+';');
// method 2
var data1 = <?php echo json_encode($data); ?>;
var plot1 = jQuery.jqplot ('Chart', [data1],
{
seriesDefaults: {
// Make this a pie chart.
renderer: jQuery.jqplot.PieRenderer,
rendererOptions: {
// Put data labels on the pie slices.
// By default, labels show the percentage of the slice.
showDataLabels: true
}
},
legend: { show:true, location: 'e' }
}
);
});
</script>
I've tried two methods, the first to put it inside a hidden field, and the second to retrieve straight from PHP. Both of which result in Uncaught. No plot target specified errors in my Chrome console.
What is it I am doing wrong here?
Thanks guys.
As Asad mentioned, my stupid mistake was that Chart was not specified as an element. So yeah if anyone else ever comes into the same problem, be sure to check that out. :)

Using php, ajax and jqplot to make a pie chart

I am attempting to make a pie chart using a php file that gets the information from MySQL, JSON encodes it, and then sends it to my JS file to make the pie chart. I have looked at most of the other questions posted here and none of them help me at all. I have attempted to re-qrite my code to match ones that seem to fit, but nothing is working.
My php file is:
$shelvDate = $_POST['shelvDate'];
$x = 0;
// get information from database for shelving chart
$shelv = $conn -> query ("SELECT sum(quantity) as qty, date_process, created_by, first_name from inventory LEFT JOIN users on users.user_id =inventory.created_by
WHERE date_process = '$shelvDate' GROUP BY created_by" );
$num_rows = $shelv->num_rows;
if($num_rows > 0){
while($row = $shelv->fetch_assoc()) {
if($row['qty'] > 0){
$qtyArray[$x] = $row['qty'];
$nameArray[$x] = $row['first_name'];
}
$x++;
$pairs = array('first_name' => $nameArray, 'qty' => $qtyArray);
} // end of while statement
} //end of if statement
$conn->close();
echo json_encode(array($pairs));
When I attempt to get the data into my ajax/js I get an error. My JS is:
$("#getRecords").live('click', function() {
var ajaxDataRenderer = function(url, plot, options) {
var ret = null;
$.ajax({
type: "POST",
async: false,
url: url,
dataType:"json",
data: ({shelvDate: $('#shelvDate').val()}),
success: function(data) {
for(var x=0; x<data.first_name.length; x++) {
var info = [data.first_name[x], data.qty[x]];
ret.push(info);
}
}); // end of ajax call
return ret;
}; // end of ajaxDataRenerer call
// The url for our json data
var jsonurl = "shelvChart.php";
var plot2 = $.jqplot('shelvChart', jsonurl,{
seriesDefaults: {
// Make this a pie chart.
renderer: jQuery.jqplot.PieRenderer,
rendererOptions: {
// Put data labels on the pie slices.
// By default, labels show the percentage of the slice.
showDataLabels: true
}
},
title: "Books Shelved",
dataRenderer: ajaxDataRenderer,
dataRendererOptions: {
unusedOptionalUrl: jsonurl
}
});
});
I am don't know what I'm doing wrong or even where to go from here as I am still new to AJAX and JS. Any help will be greatly appreciated.
Jim
It would be very useful to see a real JSON string you are getting, cause I am not sure how you can get name[object,object],qty[object,object] after calling alert(ret) or maybe you are referring to other alert?.
Anyway from what you are saying your problem is that you must make sure that the array returned by the ajaxDataRenderer function is of a proper format that is accepted by a pie chart.
Therefore, for example, inside your PHP or JavaScript code you need to make sure that the returned array ret is of the following format:
ret = [[name[0], qty[0]], [name[1], qty[1]], ...];
This way all values that are in name array will be used as labels and qty array will be used as values from which the percentage will be evaluated.
Similar approach that shows how to prepare data for a chart is shown in this answer.

Passing data from PHP class to PHPExcel via AJAX

i got stuck with OOP PHP and json data. i'm not completely new to OOP, but i can't get my head around this. if anyone can please explain to me, would be great!
i have the following grid object in PHP:
Class Grid {
var $data;
var $joins;
var $fields;
var $where;
var $table;
var $groupBy;
var $having;
var $limit;
var $order_by;
var $sort;
var $security;
var $set;
var $sql;
....
// loads data into the grid
function load() {
...
// setup the sql - bring it all together
$sql = "
SELECT $post[cols]
FROM `$table`
$joins
$where
$groupBy
$having
ORDER BY $order_by $sort
$limit
";
$this->sql = $sql;
// execute the sql, get back a multi dimensial array
$rows = $this->_queryMulti($sql);
// form an array of the data to send back
$data = array();
$data['rows'] = array();
foreach($rows as $i=>$row) {
foreach($row as $col=>$cell) {
// use primary key if possible, other wise use index
$key = $primaryKey ? $row[$primaryKey] : $i;
// primary key has an _ infront becuase of google chrome re ordering JSON objects
//http://code.google.com/p/v8/issues/detail?id=164
$data['rows']["_".$key][$col] = $cell;
}
}
...
$data['order_by'] = $order_by;
$data['sort'] = $sort;
$data['page'] = $page;
$data['start'] = $startRow + 1;
$data['end'] = $startRow + $nRowsShowing;
$data['colData'] = $colData;
$this->data = $data;
}
and it's called by AJAX callgrid.php:
$grid->load();
// here we need to add field in data[sql] = sql query, then we can pass it to toExcel() - how?
echo json_encode($grid->data);
what i'm trying to get is to be able to export current sql query (it can be all or searched results) into Excel using PHPExcel. So i've got toExcel.php with function toexcel($query) - that will take a query and export it to excel.
now - HOW do i pass sql query from grid to toexcel via AJAX?
I understand that i need to add to $data():
$data['sql'] = $sql;
what next?
UPDATE:
I'm using the following jquery grid:
http://square-bracket.com/openjs
I understand that PHPExcel should be initiated either by grid or jquery
A general idea of what you could do:
Create a button e.g.
export to Excel
Then in jquery you have to create something like:
var grid = $(".grid.digital_edit").loadGrid({...}); //or similar - what you did to load the data into the grid
$('#export').click(function() {
$.ajax({
url: "export_to_excel.php", // the url of the php file that will generate the excel file
data: grid.getData(), //or similar - based on the grid's API
success: function(response){
window.location.href = response.url;
}
})
});
The file export_to_excel.php will contain the code that generates the excel file:
This is where you'll initiate the PHPExcel class and create a file e.g. new_excel.xls
In your response array the $response['url'] will contain the absolute url to the newly created file. (http://www.example.com/files/new_excel.xls)
It may sound too complex, but try to separate your goals and achieve one at a time. E.g.
Create the button.
Then try to make a simple AJAX call when hitting the button.
Then create your export_to_excel.php file and try to work with the PHPExcel class.
Create a sample excel file based on the tutorials found.
Create an excel file based on your own data, but hard-coded in the php file.
Create the correct AJAX call that sends the wanted data to a php file.
Catch the correct AJAX call.
Pass the data from the AJAX call to the PHPExcel class.
Create the excel file.
Send back the url to the excel file.
Redirect the user to the url of the excel file.
EDIT
To help you a bit more: You need only one PHP script/file. The same one will receive the AJAX call from the javascript file, will generate the excel file and will return/respond the file url to the javascript file(in that order). A simplified example would be:
<?php
//export_to_excel.php
$data = $_POST['data']; // get the data from the AJAX call - it's the "data: grid.getData()" line from above
//... format the received data properly for the PHPExcel class
// later on in the same file:
$xls = new PHPExcel();
$xls->loadData($formattedData); //I assume that there is a similar loadData() method
$xls->exportToFile('/vaw/www/example.com/public/files/new_excel.xls'); // I assume that there is an exportToFile() method
$response = array(
'success' => true,
'url' => 'http://www.example.com/files/new_excel.xls'
);
header('Content-type: application/json');
// and in the end you respond back to javascript the file location
echo json_encode($response);
And then in javascript you display the file with this line
window.location.href = response.url; //response.url is $response['url'] from the PHP script

PHP to JSON on client side

I'm using Rob Monies 'Jquery Week Calendar' to build a calendar application.
I have a MSSQL DB a with table named 'dates' and the following fields:
id
start
end
title
I would like to query this DB in PHP and then pass the results to Javascript, Javascript will then render the events in the browser.
The Javascript needs to receive the event details in JSON format as per the following example:
{"id":1,"start": 2010-10-09T13:00:00,"end":2010-10-09T14:00:00,"title":"Lunch with Mike"},
{"id":2,"start": 2010-10-10T13:00:00,"end": 2010-10-10T14:00:00, "title":"Dev Meeting"}
So far, to keep things simple I've just returned one row from the DB at a time, however - I will need the application to be able to render multiple events, as stored in the database.
I've tried using json_encode() to put the values into a var and pass them to a Javascript var called DB_events - if I return the DB_events in an alert box on the client side I see the following;
{"id":1, "start":2010-10-09T13:00:00, "end":2010-10-09T14:00:00,"title":"Lunch with Mike"}
which looks ok, but when I do this in my code:
events : [DB_events]
It doesn't work :(
If I take PHP out of the equation, and just do the following on the client side:
var DB_events = {"id":1, "start":2010-10-09T13:00:00, "end":2010-10-09T14:00:00,"title":"Lunch with Mike"};
and return DB_events in an alert box, I get:
[object] [Object]
But when I do this:
events : [DB_events]
it works!
Back to PHP …
If I put the SQL result into PHP vars as follows:
$id = id;
$start = start;
$end = end;
$title = title;
and pass those vars to the following JS vars:
JS_id
JS_start
JS_end
JS_title
and do this on the client side:
var DB_events = {"id":JS_id, "start":JS_start, "end":JS_end,"title":JS_title};
events : [DB_events]
that also works.
As you can probably tell - I'm new to this and probably missing something very basic.
Any help, advice or information would be very much appreciated :)
Many Thanks
Tim
when you get a string representation of your object it means that you've exported it as a string not as an object.
when you get [object] [Object] it means that it is now an object, which is right!
You can do this with JSONP if you get JSON from an URL:
// send the request via <script> tag
var src = "..."; // url of the JSON output
var head = document.getElementsByTagName("head")[0];
var script = document.createElement("script");
script.setAttribute("type", "text/javascript");
script.setAttribute("src", src);
head.appendChild(script);
Or parse it as a string with JSON parser:
https://github.com/douglascrockford/JSON-js/blob/master/json2.js
var DB_events = JSON.parse( ...JSON output as a string... );
Or by directly passing it from PHP with an inline <script> block in your page:
echo "<script>";
echo "var DB_events = " . json_encode( ... ) . ";";
echo "</script>";
​
Did you use jsocn decode
http://php.net/manual/en/function.json-decode.php
You can split the result and make it differenct variables like start ,end , events etc
http://php.net/manual/en/function.explode.php

Categories