The PHP code throws the error "Data column(s) for axis #0 cannot be of type string"
<html>
<head>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Year1', 'CountGiardiaPos', 'CountCryptoPos'],
<?php
$result = mysqli_query($connection, "SELECT * FROM sqlAnnualPositives2");
if($result){
echo "CONNECTED TO CLOUD PRU DATABASE<br>";
}
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_array()) {
echo "[".$row[Year1].", ".$row[CountGiardiaPos].", ".$row[CountCryptoPos]."],";
}
}
?>
]);
var options = {
title: 'Company Performance',
curveType: 'function',
legend: { position: 'bottom' }
};
var chart = new google.visualization.LineChart(document.getElementById('curve_chart'));
chart.draw(data, options);
}
</script>
</head>
<body>
<div id="curve_chart" style="width: 1600px; height: 800px"></div>
</body>
</html>
If I run the code in a separate PHP file
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_array()) {
echo "['".$row[Year1]."', ".$row[CountGiardiaPos].", ".$row[CountCryptoPos]."],";
}
}
I get the correct data:
['2003', 0, 207],['2005', 0, 29],['2006', 1, 59],['2007', 1, 148],['2008', 1, 109],['2009', 72, 71],['2010', 450, 261],['2011', 1934, 967],['2012', 662, 206],['2013', 627, 487],['2014', 735, 233],['2015', 720, 350],['2016', 855, 503],['2017', 836, 593],['2018', 983, 950],['2019', 920, 508],['2020', 291, 97],
Where is the error in the code?
the issue is that you're printing "CONNECTED TO CLOUD PRU DATABASE<br>" in the middle of your data array, here...
var data = google.visualization.arrayToDataTable([ // <-- ARRAY STARTS HERE
['Year1', 'CountGiardiaPos', 'CountCryptoPos'],
<?php
$result = mysqli_query($connection, "SELECT * FROM sqlAnnualPositives2");
if($result){
// PRINTING THIS HERE WILL MESS UP YOUR ARRAY
echo "CONNECTED TO CLOUD PRU DATABASE<br>";
}
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_array()) {
echo "[".$row[Year1].", ".$row[CountGiardiaPos].", ".$row[CountCryptoPos]."],";
}
}
?>
]); // <-- ARRAY ENDS HERE
but let's back up. first, it is not recommended to manually build json data by concatenating strings and variables.
echo "[".$row[Year1].", ".$row[CountGiardiaPos].", ".$row[CountCryptoPos]."],";
instead, build the array in php and use json_encode to print it on the page.
<?php
$result = mysqli_query($connection, "SELECT * FROM sqlAnnualPositives2");
$rows = array();
if ($result->num_rows > 0) {
// add column headings
$rows[] = array('Year1', 'CountGiardiaPos', 'CountCryptoPos');
// output data of each row
while($row = $result->fetch_array()) {
$rows[] = array($row[Year1], $row[CountGiardiaPos], $row[CountCryptoPos]);
}
}
?>
<html>
<head>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
// use json_encode to build data table
var data = google.visualization.arrayToDataTable(<?php echo json_encode($rows); ?>);
var options = {
title: 'Company Performance',
curveType: 'function',
legend: { position: 'bottom' }
};
var chart = new google.visualization.LineChart(document.getElementById('curve_chart'));
chart.draw(data, options);
}
</script>
</head>
<body>
<div id="curve_chart" style="width: 1600px; height: 800px"></div>
</body>
</html>
I'm going through a bit of a learning process, in order to create a small database backed reporting system for my company.
The intent is to draw a multi line chart using Google Charts, based on a mysql database.
I've managed to get the data to echo from the mysql database, but it's not generating the chart. All I get is the echo, and a blank space where the chart should be. The echo is shown for debugging purposes.
Here is the code :
<?php include 'confile.php';
$qry = "SELECT time,p1,p2,p3,p4 from $db WHERE date = '2016-03-02' ORDER BY time ASC";
$result = $conn->query($qry);
if($result === FALSE) {
echo mysql_errno($result) .": ". mysql_error($result) ."/n";
die(mysql_error());
}
$rows = array();
$table = array();
$table['cols'] = array(
array('label' => 'Time', 'type' => 'datetime'),
array('label' => 'Probe 1', 'type' => 'number'),
array('label' => 'Probe 2', 'type' => 'number'),
array('label' => 'Probe 3', 'type' => 'number'),
array('label' => 'Probe 4', 'type' => 'number')
);
while($r = mysqli_fetch_assoc($result)) {
$temp = array();
$temp[] = array($r['time']);
$temp[] = array($r['p1']);
$temp[] = array($r['p2']);
$temp[] = array($r['p3']);
$temp[] = array($r['p4']);
$rows[] = array('c' => $temp);
}
$table['rows'] = $rows;
$jsonTable = json_encode($table);
echo $jsonTable;
?>
<html>
<head>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script type="text/javascript">
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = new google.visualization.DataTable(<?$jsonTable?>);
var options = {
title: 'Recorded Temperatures',
legend: {position: 'bottom' },
width: 800,
height: 600
};
var chart = new google.visualization.Table(document.getElementById('curve_chart'));
chart.draw(data, options);
}
</script>
</head>
<body>
<div id="curve_chart" style="width: 900px; height: 500px"></div>
</body>
</html>
And this is the 'echo' output
{"cols":[{"label":"Time","type":"datetime"},{"label":"Probe 1","type":"number"},{"label":"Probe 2","type":"number"},{"label":"Probe 3","type":"number"},{"label":"Probe 4","type":"number"}],"rows":[{"c":[["03:02:07"],["270.26"],["298.40"],["111.54"],["228.06"]]},{"c":[["03:28:42"],["273.23"],["190.43"],["245.69"],["283.21"]]},{"c":[["07:26:04"],["144.33"],["217.26"],["206.53"],["167.68"]]},{"c":[["12:13:20"],["153.15"],["277.23"],["167.20"],["240.88"]]}]}
This is test data, using a test query on the db. Once I understand the formatting to render the chart, it will be setup to allow the user to select which date to view, etc.
This was the closest existing question I can find, but doesn't seem to answer the question.
Not able to generate a Google Chart using MySQL table data as the data source
Following the answer of #MickMackusa, I managed to hack this together to get it to work, by ensuring the mysql/php array was output in a manner acceptable to Google Charts.
Thanks to #MickMacUSA for his assistance.
The final, working code, is below.
<?php include 'confile.php';
$qry = "SELECT time,p1,p2,p3,p4 from $db WHERE date = '2016-04-16' ORDER BY time ASC";
$result = $conn->query($qry);
if($result === FALSE) {
echo mysqli_errno($result) .": ". mysqli_error($result) ."/n";
die(mysqli_error());
}
$i = 0; //iteration counter - start at 0
$totalRows = mysqli_num_rows($result); // we need this to know when to change the output
$targetRows = $totalRows - 1; //row indies start from 0, not 1.
foreach ($result as $row){
$comTime = str_replace(":",",",$row['time']); // for each row, remove the : and put , in its place
if ($targetRows == $i) { // if the index is the same value as the target (ie, it's the last row)...
$temp = "[[".$comTime."],".($row['p1']).",".($row['p2']).",".($row['p3']).",".($row['p4'])."]". PHP_EOL;
} else {
$temp = "[[".$comTime."],".($row['p1']).",".($row['p2']).",".($row['p3']).",".($row['p4'])."],". PHP_EOL;
}
$i = $i + 1;
$rows[] = $temp;
}
$table = $rows;
$data = implode($table); //format the table as a single string, with line returns
//echo $i;
//echo $data;
?>
<html>
<head>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
</head>
<body>
<div id="chart" style="width: 900px; height: 500px"></div>
<script type="text/javascript">
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart(){
var data = new google.visualization.DataTable();
data.addColumn('timeofday','Time');
data.addColumn('number','Probe 1');
data.addColumn('number','Probe 2');
data.addColumn('number','Probe 3');
data.addColumn('number','Probe 4');
data.addRows([
<?php echo $data; ?> //dump the result into here, as it's correctly formatted
]);
var options = {
title: 'Recorded Temperatures',
legend: { position: 'bottom' },
width: 900,
height: 500,
hAxis: { format: 'hh:mm:ss' }
};
var chart = new google.visualization.LineChart(document.getElementById('chart'));
chart.draw(data, options);
}
</script>
</body>
</html>
Your number values must be formatted differently and you want timeofday not datetime.
According to: https://developers.google.com/chart/interactive/docs/reference#dataparam
Format your data to look like this:
{cols:
[
{"label":"Time","type":"timeofday"},
{"label":"Probe 1","type":"number"},
{"label":"Probe 2","type":"number"},
{"label":"Probe 3","type":"number"},
{"label":"Probe 4","type":"number"}
],
rows:
[
{c:[{v:[03,02,07],f:'03:02:07'},{v:270.26},{v:298.40},{v:111.54},{v:228.06}]},
{c:[{v:[03,28,42],f:'03:28:42'},{v:273.23},{v:190.43},{v:245.69},{v:283.21}]},
{c:[{v:[07,26,04],f:'07:26:04'},{v:144.33},{v:217.26},{v:206.53},{v:167.68}]},
{c:[{v:[12,13,20],f:'12:13:20'},{v:153.15},{v:277.23},{v:167.20},{v:240.88}]}
]
}
And you must echo it in the javascript:
change:
<?$jsonTable?>
to:
<?php echo $jsonTable; ?>
And put your javascript code block just before your </body> tag.
This is the full working code using the above data format that I tested on my server:
<html>
<head>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
</head>
<body>
<div id="curve_chart" style="width: 900px; height: 500px"></div>
<script type="text/javascript">
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart(){
var data = new google.visualization.DataTable(
{cols:[
{"label":"Time","type":"timeofday"},
{"label":"Probe 1","type":"number"},
{"label":"Probe 2","type":"number"},
{"label":"Probe 3","type":"number"},
{"label":"Probe 4","type":"number"}
],
rows:[
{c:[{v:[03,02,07],f:'03:02:07'},{v:270.26},{v:298.40},{v:111.54},{v:228.06}]},
{c:[{v:[03,28,42],f:'03:28:42'},{v:273.23},{v:190.43},{v:245.69},{v:283.21}]},
{c:[{v:[07,26,04],f:'07:26:04'},{v:144.33},{v:217.26},{v:206.53},{v:167.68}]},
{c:[{v:[12,13,20],f:'12:13:20'},{v:153.15},{v:277.23},{v:167.20},{v:240.88}]}
]
});
var options = {
title: 'Recorded Temperatures',
legend: { position: 'bottom' },
width: 900,
height: 500,
hAxis: { format: 'hh:mm:ss' }
};
var chart = new google.visualization.LineChart(document.getElementById('curve_chart'));
chart.draw(data, options);
}
</script>
</body>
</html>
This is an alternative format that will be simpler/clearer/easier to build/comprehend using your mysqli results:
<html>
<head>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
</head>
<body>
<div id="curve_chart" style="width: 900px; height: 500px"></div>
<script type="text/javascript">
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart(){
var data = new google.visualization.DataTable();
data.addColumn('timeofday','Time');
data.addColumn('number','Probe 1');
data.addColumn('number','Probe 2');
data.addColumn('number','Probe 3');
data.addColumn('number','Probe 4');
data.addRows([
[[03,02,07],270.26,298.40,111.54,228.06],
[[03,28,42],273.23,190.43,245.69,283.21],
[[07,26,04],144.33,217.26,206.53,167.68],
[[12,13,20],153.15,277.23,167.20,240.88]
]);
var options = {
title: 'Recorded Temperatures',
legend: { position: 'bottom' },
width: 900,
height: 500,
hAxis: { format: 'hh:mm:ss' }
};
var chart = new google.visualization.LineChart(document.getElementById('curve_chart'));
chart.draw(data, options);
}
</script>
</body>
</html>
See the SO Demo provided by WhiteHat:
google.charts.load('current', {
callback: drawChart,
packages: ['corechart', 'table']
});
function drawChart() {
var data = new google.visualization.DataTable({cols: [
{"label":"Time","type":"timeofday"},
{"label":"Probe 1","type":"number"},
{"label":"Probe 2","type":"number"},
{"label":"Probe 3","type":"number"},
{"label":"Probe 4","type":"number"}
],
rows: [
{c:[{v:[03,02,07],f:'03:02:07'},{v:270.26},{v:298.40},{v:111.54},{v:228.06}]},
{c:[{v:[03,28,42],f:'03:28:42'},{v:273.23},{v:190.43},{v:245.69},{v:283.21}]},
{c:[{v:[07,26,04],f:'07:26:04'},{v:144.33},{v:217.26},{v:206.53},{v:167.68}]},
{c:[{v:[12,13,20],f:'12:13:20'},{v:153.15},{v:277.23},{v:167.20},{v:240.88}]}
]
});
var table = new google.visualization.Table(document.getElementById('chart_0'));
table.draw(data);
var options = {
title: 'Recorded Temperatures',
legend: {position: 'bottom' },
width: 800,
height: 600,
hAxis: {
format: 'hh:mm:ss'
}
};
var chart = new google.visualization.LineChart(document.getElementById('chart_1'));
chart.draw(data, options);
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_0"></div>
<div id="chart_1"></div>
I am trying to make orgchart in my code, a have not any idea about this chart. I want to make a a tree like chart, and want data from mysql table.
Table is : treechart
id name treeid
1 a 1
2 aa 11
3 aaa 111
4 aaaa 1111
5 ab 12
6 aba 121
7 abb 122
8 ac 13
My code is as below :
<html>
<head>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
google.charts.load('current', {packages:["orgchart"]});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Name');
data.addColumn('string', 'Manager');
data.addColumn('string', 'ToolTip');
// For each orgchart box, provide the name, manager, and tooltip to show.
<?php
include get_template_directory()."/connect/connect.php";
$result = mysql_query("select * from treechart order by id asc");
$members = array();
$demo = "[\n";
while ($row = mysql_fetch_array($result))
{
$members[$row[2]] = $row[1];
}
function search_tree($searchkey)
{
return $members[$searchkey];
}
foreach($members as $key=>$member)
{
if(strlen($key)==1)
{
$demo = $demo."['".$member."','','".$member."'],\n";
$one = $member;
}
if(strlen($key)==2)
{
$demo = $demo."['".$member."','".$one."',''],\n";
}
if(substr($key,0,2)=="11")
{
if(strlen($key)==3)
{
$newkey = search_tree("11");
echo $newkey."---.";
}
}
$oldkey = strlen($key);
}
$demo = substr($demo,0,strlen($demo)-2);
$demo = $demo."]";
print_r($newdemo);
?>
data.addRows(<?php echo $demo; ?>);
// Create the chart.
var chart = new google.visualization.OrgChart(document.getElementById('chart_div'));
// Draw the chart, setting the allowHtml option to true for the tooltips.
chart.draw(data, {allowHtml:true});
}
</script>
</head>
<body>
<div id="chart_div"></div>
</body>
</html>
My problem is in $newkey I can't any value, I want the value of 11,12,13 keys value in $newkey. And I have very big amount of data in table, so if anyone have any short coding idea, then help me in my code.
You have to define parent column in your table
id | parrentId | Name
Here is an example
var orgchart = new getOrgChart(document.getElementById("people"),{
dataSource: [
{ id: 1, parentId: null, Name: "1"},
{ id: 2, parentId: 1, Name: "2"},
{ id: 3, parentId: 1, Name: "3"}]
});
html,
body {
margin: 0px;
padding: 0px;
height: 100%;
overflow: hidden;
}
#people {
width: 100%;
height: 100%;
}
<link href="http://www.getorgchart.com/GetOrgChart/getorgchart/getorgchart.css" rel="stylesheet"/>
<script src="http://www.getorgchart.com/GetOrgChart/getorgchart/getorgchart.js"></script>
<div id="people"></div>
I want to generate graph for my static data. I am using Google Chart for doing this. Here is the google chart code
<html>
<head>
<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 = google.visualization.arrayToDataTable([
['Task', 'Hours per Day'],
['Work', 11],
['Eat', 2],
['Commute', 2],
['Watch TV', 2],
['Sleep', 7]
]);
var options = {
title: 'My Daily Activities'
};
var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
</head>
<body>
<div id="chart_div" style="width: 900px; height: 500px;"></div>
</body>
</html>
But i want to put my code in this. I am not getting how to do it. Here is my code
<?php
echo '<div align="center" style="width:100%; padding-top:20px;">
<table width="100%" cellspacing="0" cellpadding="0" border="0">
<tr>
<td class=tddash>10 latest purchase orders</td>
</tr>
<tr>
<td>';
$SQL = 'SELECT purchorders.orderno,
suppliers.suppname,
purchorders.orddate,
purchorders.deliverydate,
purchorders.initiator,
purchorders.requisitionno,
purchorders.allowprint,
purchorders.status,
suppliers.currcode,
currencies.decimalplaces AS currdecimalplaces,
SUM(purchorderdetails.unitprice*purchorderdetails.quantityord) AS ordervalue
FROM purchorders
INNER JOIN purchorderdetails
ON purchorders.orderno = purchorderdetails.orderno
INNER JOIN suppliers
ON purchorders.supplierno = suppliers.supplierid
INNER JOIN currencies
ON suppliers.currcode=currencies.currabrev
WHERE purchorders.orderno=purchorderdetails.orderno
GROUP BY purchorders.orderno,
suppliers.suppname,
purchorders.orddate,
purchorders.initiator,
purchorders.requisitionno,
purchorders.allowprint,
purchorders.status,
suppliers.currcode,
currencies.decimalplaces LIMIT 5';
$SalesOrdersResult2 = DB_query($SQL,$db);
$Total = 0;
echo '<table width="100%" celpadding="2" class="selection">';
echo '<tbody><tr><th> Supplier </th><th>Order Date</th><th>Delivery Date</th><th>Initiator</th><th>Order Total</th><th>Status</th></tr></tbody> ';
$k=0;
while ($row = DB_fetch_array($SalesOrdersResult2))
//while ($row = mysql_fetch_array($SalesOrdersResult))
{
if ($k == 1){
echo '<tr class="EvenTableRows">';
$k = 0;
} else {
echo '<tr class="OddTableRows">';
$k = 1;
}
$FormatedOrderValue2 = locale_number_format($row['ordervalue'],$row['currdecimalplaces']);
$Total += $row['ordervalue'];
//$FormatedOrderValue1 = locale_number_format($myrow['ordervalue'],$_SESSION['CompanyRecord']['decimalplaces']);
$FormatedOrderDate1 = ConvertSQLDate($row['orddate']);
$FormatedDelDate1 = ConvertSQLDate($row['deliverydate']);
echo ' <td> ' . $row['suppname'] . ' </td>';
echo ' <td>$FormatedOrderDate1</td><td>$FormatedDelDate1</td><td> ' . $row['initiator'] . ' </td><td>$FormatedOrderValue2</td><td> ' . $row['status'] . ' </td> ';
}
echo '<tr><td colspan="3">Total---</td><td colspan="2">$Total</td></tr></tbody>';
echo '</table></td>';
echo' </tr>
</table>
</div>';
Can somebody plz help me in this?
* EDITED *
echo '<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js" type="text/javascript"></script>';
echo ' <script type="text/javascript">
function drawChart() {
var jsonData = $.ajax({
url: "1getData.php",
dataType:"json",
async: false
}).responseText;
alert(jsonData);
var data = new google.visualization.DataTable(jsonData);
var view = new google.visualization.DataView(data);
view.setColumns([0, 3]);
var chart = new google.visualization.ColumnChart(document.getElementById("chart_div"));
chart.draw(view, {width:400, height:240});
}
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
</script>';
echo '</head>';
<div id="chart_div" ></div>
1getData.php
<?php
$PageSecurity=0;
include('includes/session.inc');
if (!isset($RootPath)){
$RootPath = dirname(htmlspecialchars($_SERVER['PHP_SELF']));
if ($RootPath == '/' or $RootPath == "\\") {
$RootPath = '';
}
}
$SQL = "SELECT workorders.wo, woitems.stockid, stockmaster.description, stockmaster.decimalplaces, woitems.qtyreqd, woitems.qtyrecd, workorders.requiredby, workorders.startdate
FROM workorders
INNER JOIN woitems ON workorders.wo = woitems.wo
INNER JOIN stockmaster ON woitems.stockid = stockmaster.stockid
ORDER BY workorders.wo";
$searchresult = DB_query($SQL, $db);
$table=array();
$table['cols']=array(
array('label'=>'ITEM', type=>'string'),
array('label'=>'Description', type=>'string'),
array('label'=> 'QTY Required', type=>'number'),
array('label'=>'QTY Outstanding', type=>'number')
);
$rows=array();
while ($row = DB_fetch_array($searchresult))
{
$qreq = locale_number_format($row['qtyreqd'],$row['decimalplaces']);
$qout = locale_number_format($row['qtyreqd']-$row['qtyrecd'],$row['decimalplaces']);
$temp=array();
$temp[]=array('v' => $row['stockid']);
$temp[]=array('v' => $row['description']);
$temp[]=array('v' => $row['qtyreqd']);
$temp[]=array('v' => ($row['qtyreqd']-$row['qtyrecd']));
$rows[]=array('c' => $temp);
}
$table['rows']=$rows;
$jsonTable = json_encode($table);
print $jsonTable;
?>
but it displays only two columns, where as i want to display 3
JAVA SCRIPT
<script type="text/javascript">
function drawChart() {
var jsonData = $.ajax({
url: "1getData.php",
dataType:"json",
async: false
}).responseText;
alert(jsonData);
var data = new google.visualization.DataTable(jsonData);
var view = new google.visualization.DataView(data);
view.setColumns([0,3]);
var chart = new google.visualization.ColumnChart(document.getElementById("chart_div"));
chart.draw(view, {width:400, height:240});
}
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
</script>
Your line view.setColumns([0, 3]) tells Google charts to only display the first and fourth column in your data. Add the columns you want to display to the array.
I'm just trying to figure out to format my labels to be shown as a currency and not just a number:
echo ' <script type="text/javascript" src="http://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", "ZipCode");
data.addColumn("number", "Sales");
data.addRows('.$count.');';
$i = 0;
foreach ($results as $r) {
$p = (($r->report_trans_amount / $total) * 100);
$pd = strval(number_format($p, 1));
echo ' data.setValue(' . $i . ', 0, "' . $r->member_address_zip_code .
' - ' . $pd . '%");';
echo ' data.setValue(' . $i . ', 1, ' . $r->report_trans_amount . ');';
$i++;
}
echo ' var chart = new google.visualization.PieChart(
document.getElementById("chart_div"));
chart.draw(data, {width:900, height:500, is3D:true});
}
</script>
<div id="chart_div"></div>
';
I would like the Sales column to be shown as a USD currency value. How can I do that? I see how to do it using the URL request, but that does not help this situation.
I just can't seem to find any good example on this.
it looks like you might want to look at setFormattedValue
http://code.google.com/apis/chart/interactive/docs/reference.html#DataTable_setFormattedValue
and for the format stuff look at
http://code.google.com/apis/chart/interactive/docs/reference.html#formatters
I haven't tried this out, but from what I can tell this could work for you:
echo '
<script type="text/javascript" src="http://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", "ZipCode");
data.addColumn("number", "Sales");
data.addRows('.$count.');
var formatter = new google.visualization.NumberFormat({prefix: \'$\'});
formatter.format(data, 1);';
$i = 0;
foreach($results as $r){
$p = (($r->report_trans_amount / $total) * 100);
$pd = strval(number_format($p, 1));
echo 'data.setValue('.$i.', 0, "'.$r->member_address_zip_code.' - '.$pd.'%");';
//echo 'data.setFormattedValue('.$i.', 1, formatter);'; // might not need this with the formatter.format above
echo 'data.setValue('.$i.', 1, '.$r->report_trans_amount.');';
$i++;
}
echo ' var chart = new google.visualization.PieChart(document.getElementById("chart_div"));
chart.draw(data, {width:900, height:500, is3D:true});
}
</script>
<div id="chart_div"></div>
';
references:
http://code.google.com/p/google-visualization-api-issues/issues/detail?id=282