I have a page listing in table format some sales data. I want to include a chart. Since I already have to retrieve the data for the table I figured I would also build the array for google and put it in a hidden input to retrieve it with javascript. So this is the javascript
// Load the Visualization API and the piechart package.
google.load('visualization', '1.0', {'packages':['corechart']});
google.setOnLoadCallback(drawChart);
function drawChart() {
var chartD = document.getElementById('chartD').value;
var data = google.visualization.arrayToDataTable([chartD]);
var options = {'title':'Sales'};
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
This is the input I get the data from
<input type="hidden" id="chartD" value="['Date', 'Units Sold'],
['03-01', 12.00], ['03-04', 32.00], ['03-06', 6.00],
['03-08', 19.00], ['03-11', 10.00], ['03-13', 5.00], ['03-15', 0]">
But when I run this I get an error Not a valid 2D array I then copied the value straight from the view page source like this
var data = google.visualization.arrayToDataTable([['Date', 'Units Sold'],
['03-01', 12.00], ['03-04', 32.00], ['03-06', 6.00], ['03-08', 19.00],
['03-11', 10.00], ['03-13', 5.00], ['03-15', 0]]);
And that worked just fine. Does anyone have any idea what the problem is?
This is normal javascript functionality and nothing unique to Google or otherwise odd.
Take your HTML hidden div element and toss it in a document:
<input type="hidden" id="chartD" value="['Date', 'Units Sold'],
['03-01', 12.00], ['03-04', 32.00], ['03-06', 6.00],
['03-08', 19.00], ['03-11', 10.00], ['03-13', 5.00], ['03-15', 0]">
Now test this javascript:
var chartD = document.getElementById('chartD').value;
var array = new Array(['Date', 'Units Sold'], ['03-01', 12.00], ['03-04', 32.00], ['03-06', 6.00], ['03-08', 19.00], ['03-11', 10.00], ['03-13', 5.00], ['03-15', 0]);
var array2 = new Array(chartD);
alert(array.length);
alert(array2.length);
This is the exact same behavior with standard javascript.
When you define the object with copy-paste, you get an array with 8 rows, 2 columns (hence length 8).
When you define the object with a string, you get an array that has one row and one column (containing a really long string).
Why would you expect Google to act any differently?
You either need to:
Pass in a fully formed 2D array to google
Pass in an array-defining string in by hand
This is all covered in the documentation.
Expecting Google to have some funky behavior different from javascript probably isn't the best approach.
Related
I'm using google charts to output a very simple pie chart
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Games', 'Number'],
['Win', 11],
['Lose', 2]
]);
var options = {
title: 'Win/Lose Ratio'
};
var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
However, in place of the values for Win and Lose, I want to pull 2 numbers out of my database. This doesn't need any kind of loop, just a way to reference 2 specific fields on a row instead of the values 11 and 2. This is the SQL query I'm using to get those two values
$qry =("SELECT games_won, games_lost FROM Members where member_id = '".$_SESSION['SESS_MEMBER_ID']."'");
$result = mysql_query($qry);
$row = mysql_fetch_array($result);
$won = $row[games_won];
$lost = $row[games_lost];
Does anyone know how to do this?
I've had a look at a lot of other FAQ's on the subject but they all deal with a collection of values in the same field and looping through severals rows of data, as opposed to referencing specific entries in the database.
Thanks in advance!
Have you tried this:
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Games', 'Number'],
['Win', <?php echo($won); ?>],
['Lose', <?php echo($lost); ?>]
]);
var options = {
title: 'Win/Lose Ratio'
};
var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
All you are doing is grabbing the values, then echoing them out into your JavaScript. Please do note that I am not error checking, that is something you will need to think about when directly injecting values into HTML or JavaScript!
A better way of doing this is writing your code as a RESTful API. Have your SQL code in a place that you can send a member_id as a GET request. That, in turn, can print out the games won/lost inside JSON. Than, you can preform an AJAX request and grab those values to populate your table (just reference the values inside the returned JSON as regular JavaScript variables).
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);
I would like to have a Google pie chart on my website. The pie chart would be filled with data from the database. I was loooking at some examples at https://developers.google.com/chart/interactive/docs/php_example, but I'm lost when it comes to the JSON format.
Here are some examples:
<html>
<head>
<!--Load the AJAX API-->
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript" src="jquery-1.6.2.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>
And here is the snippet where I get lost (getData.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
?>
I have data stored in a database and not in JSON format. How do I work with the JSON format using MySQL database queries? If you have some examples or demos, I would appreciate it.
The first thing to do would be to have a look at the PHP manual about the json_encode() method. It provides examples on how to generate JSON with PHP.
Here is a short example from another similar SO question:
// Get your data from DB
$sth = mysql_query("SELECT ...");
// Create an array
$rows = array();
// Loop over the DB result and add it to your array
while($r = mysql_fetch_assoc($sth)) {
$rows[] = $r;
}
// Use json_encode() to turn the array into JSON
print json_encode($rows);
If you need to rename your database columns, so that your JSON-data get other names on the properties than those used in your DB, you can use AS in your SQL.
SELECT blog_title as title ...
just echo php result in
var data = new google.visualization.DataTable([<?php echo $result ;?>]);
u will get data from database as per as
below format
['Task', 'Hours per Day'],
['Work', 11],
['Eat', 2],
['Commute', 2],
['Watch TV', 2],
['Sleep', 7]
i think it's useful to u ,i am use same logic in heat map
I have a specific array that php needs to access and write to a file. I also want to be able to call the php to get the array info back. I use JSON.strigify to store the array in a string, but i cant figure out how to send it to a server with php. I have very little php experience and i tried:
<script language="javascript">
var COMMENTS_FOR_DISPLAY = new Array('Have fun with this code: Chris');
// Adds a new comment, name pair to the Array feeding textualizer.
function add_comment() {
// Retrieve values and add them to Array.
var new_comment = $('#kwote').val();
var new_name = $('#name').val();
COMMENTS_FOR_DISPLAY.push(new_comment + ': ' + new_name);
// Reset <input> fields.
$('#kwote').val('');
$('#name').val('');
var arrayAsString = JSON.stringify(COMMENTS_FOR_DISPLAY);
}
$(document).ready(function() {
var txt = $('#txtlzr'); // The container in which to render the list
var options = {
duration: 5, // Time (ms) each blurb will remain on screen
rearrangeDuration: 5, // Time a character takes to reach its position
effect: 'random', // Animation effect the characters use to appear
centered: true // Centers the text relative to its container
}
txt.textualizer(COMMENTS_FOR_DISPLAY); // textualize it!
txt.textualizer('start'); // start
});
</script>
in main.php i put:
<?php
$kwoteString = $_GET["arrayAsString"];
echo $kwoteString;
?>
I used echo to see if i was getting any output,but i wasn't. It could be a very simple fix, maybe im missing a header or something telling my html document to read main.php?? any help would be appreciated!
Use jquery with
$.post(url,params);
there are many tutorials around the web and stack overflow itself.
Here the doc:
http://api.jquery.com/jQuery.post/
you can add a hiddenField and set the string to the hidden field.
php code will read the value from hidden field.
I'm trying to read in values from a db using php (mySQL) then have them show on a graph in flot. I know the values are read in correctly and I'm not getting any errors but the graph won't show.
Little help?
Thanks in advance.
<?php
while ($row = mysql_fetch_array($result, MYSQL_NUM)) {
$graphdata[] = array( (int)$row[0], (int)$row[1] );
}
?>
/////
<div id="placeholder" style="width:600px;height:300px"></div>
<script language="javascript" type="text/javascript">
var dataset1 = <?php echo json_encode($graphdata);?>;
var data = [
{
label: "Random Values",
data: dataset1
}
];
var plotarea = $("#placeholder");
$.plot( plotarea , data);
</script>
The contents of your pastebin show that the JSON string you're outputting is invalid JSON.
var data = [{ label: "Random Values",data: dataset1}];
will validate if it's changed to:
var data = [{"label": "Random Values","data": "dataset1"}]
That's just an example, but I suspect that Flot is looking for a slightly different format, so you'll have to verify exactly what they're looking for against their documentation. I'm going through the same exercise right now with FusionCharts, so I'm feeling your pain. jsonlint.com is your friend on this one, output your JSON and verify it frequently. I'd also recommend that to initially get it working, start with just a string of JSON (even one that you copy from their examples) that you put right in your code. Get the chart working first, then work on getting your PHP to duplicate the example JSON string separately.
Try delaying creating the graph until the DOM is loaded:
jQuery(document).ready(function ($){
var plotarea = $("#placeholder");
$.plot( plotarea , data);
});