How to include PHP in Javascript; Google Chart API - php

I am working with the google chart visualization API.
I have a variable in php:
`$value`
which contains the following:
['0',0, 0],['1',65, 35],['2',88, 35],['3',66, 35],['4',35, 35],['5',99, 100]
I want to use this $value below in data.addRows as follows however the output I am getting is blank
<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', 'Period');
data.addColumn('number', 'Sales');
data.addColumn('number', 'Expenses');
data.addRows([
<?php echo $value ?>
]);
var options = {
width: 400, height: 240,
title: 'Company Performance'
};
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
After some research it seems it is Ajax I am trying to attempt. Is this correct? Is there a simple way I can return the value $value to data.addRow??
Here is the process to which $value is set:
$i = "0";
$period = "0";
$chartrow = array();
$unitpriceNumR = 3
while ($i<3)
{
$chartrow[$i] = "['".$period."',".$sPrice[$i].", ".$uPrice[$i]."]";
$period++;
$i++;
}
switch ($currentStage)
{
case "0":
$value = $chartrow[0];
break;
case "1":
$value = $chartrow[0];
break;
case "2":
$value = $chartrow[0].",".$chartrow[1];
break;
}
In this example if $currentStage = "2" then $value is set to ['0',0, 0],['1',65, 35]
Ok now I have even tried a copy and paste of google code into my file and still no success of seeing a graph. (code taken from:http://code.google.com/intl/en-EN/apis/chart/interactive/docs/gallery/linechart.html)
<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', 'Sales');
data.addColumn('number', 'Expenses');
data.addRows([
['2004', 1000, 400],
['2005', 1170, 460],
['2006', 860, 580],
['2007', 1030, 540]
]);
var options = {
width: 400, height: 240,
title: 'Company Performance'
};
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
Using this code
$chartrow = array();
for ($i = 0; $i < 3; $i++ )
{
$chartrow[] = array((string) $i, $sPrice[$i], $uPrice[$i]);
echo $chartrow;
}
results in $chartrow displaying the word "Array" to the screen.

Please have a look at the JSON encode function provided with PHP. This will let you echo or print out a JSON encoded string that JavaScript transforms into a native object.
$value = array(
array('0', 0, 0),
array('1', 65, 35),
array('2', 88, 35),
...
);
...
data.addColumn('number', 'Sales');
data.addColumn('number', 'Expenses');
// Change this and the following lines to:
data.addRows(<?php print json_encode($value); ?>);
EDIT
$i = 0;
$chartrow = array();
$unitpriceNumR = 3
for (; $i < 3; $i++ )
$chartrow[] = array((string) $i, $sPrice[$i], $uPrice[$i]);
switch ($currentStage) {
case "0":
case "1":
$value = $chartrow[0];
break;
case "2":
$value = array_slice($chartrow, 0, 2);
default:
// You should have some default value, seriously!!!
}
// Then go the json_encode way, it's safer and easier to maintain!
...
data.addColumn('number', 'Sales');
data.addColumn('number', 'Expenses');
// Change this and the following lines to:
data.addRows(<?php print json_encode($value); ?>);

Change [<?php echo $value ?>] to <?php echo json_encode($value) ?>
echo $value produces Array(5) because PHP doesn't natively know how to represent an array as a string.
echo json_encode($value) produces:
[['0',0, 0],['1',65,35],['2',66,35],['4',35,35],['5',99, 100]]
so you don't need brackets around the <?php ... ?>.
http://php.net/manual/en/function.json-encode.php
EDIT: thanks for clarifying how the PHP variables are formed.
The problem is that you're manually converting arrays into strings, when you should let $json_encode do all of the work for you.
Revised version of the PHP code:
$chartrow = array();
$unitpriceNumR = 3;
for ($i=0; $i<=2; $i++)
$chart_row[$i] = array($i, $sPrice[$i], $uPrice[$i];
switch ($currentStage)
{
case '0':
case '1':
$value = $chartrow[0];
break;
case '2':
$value = array($chartrow[0], $chartrow[1]);
break;
}
EDIT2: I tried what you did (replacing the php block with what we expect the php block to produce) and it didn't work for me either. Firebug says 'Container is not defined' in Google's own code.
You forgot to add a div to your document. Add <div id='chart_div'></div> after the script.
So we're on the same page: http://jsfiddle.net/daemon/nnpeE/

Here is the answer to this problem
PHP: How to pass multiple variables to an array?

Whenever I have values like that I do this as my first script on the page and it seems to work for me. It also allows me to inspect what is going on with the PHP instead of the variable being hidden in some function. Note that this will create a global variable which might be not what you want.
<script>
var a = [<?php echo($var1) ?>];
</script>
EDIT:
I got your PHP code to work for me. The changes I made was I converted $i to just 0 not "0" The same goes for the switch statement . Also line 4 needs a semicolon after it. Then I put this
<script>
var a = [<?php echo($value) ?>];
</script>
And the output in the page was
<script>
var a = [['0',, ],['1',, ]];
</script>

Related

how to use mysql data on google charts

I am trying to create a bar chart using google charts and mysqli. But my code is not working when I try to insert php in the googlecharts it is no longer showing up on the webpage.
my code:
<!--GOOGLE CHARTS-->
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></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 corechart package.
google.charts.load('current', {'packages':['corechart']});
// Set a callback to run when the Google Visualization API is loaded.
google.charts.setOnLoadCallback(drawChart);
// Callback that creates and populates a data table,
// instantiates the pie chart, passes in the data and
// draws it.
function drawChart() {
//PHP
<?php
if(isset($_GET['id'])) {
$ID= 'id';
$childId=$_GET['id'];
$rowId=$_GET['id'];
$chartsql = "SELECT `feis_entered`, `competition_level1`, `dance_name1`, `firstpl_score1`, `2ndpl_score1`, `3rdpl_score1` FROM `mark_cards1` WHERE id = '$rowId'";
$chartres = mysqli_query($con,$chartsql);
$chartrow=mysqli_fetch_array($chartres);
if($chartres){
$compName = '.$chartrow["feis_entered"].';
$compLvl = '.$chartrow["competition_level1"].';
$danceName = '.$chartrow["dance_name1"].';
$first = '.$chartrow["firstpl_score1"].';
$second = '.$chartrow["2ndpl_score1"].';
$third = '.$chartrow["3rdpl_score1"].';
}
}
?>
// Create the data table.
var data = new google.visualization.DataTable();
data.addColumn('string', 'Ranking');
data.addColumn('number', 'Score');
data.addRows([
['1st Place', <?php echo $first;?>],
['2nd Place', <?php echo $second;?>],
['3rd Place', <?php echo $third;?>]
]);
var data = google.visualization.arrayToDataTable([
['Element', 'Score', { role: 'style' }],
[ '1st Place', <?php echo $first;?>, 'color: #91b224',],
[ '2nd Place', <?php echo $second;?>, 'color: #91b224',],
[ '3rd Place', <?php echo $third;?>, 'color: #91b224',],
]);
// Set chart options
var options = {title:'<?php echo $compName - $compLvl - $danceName;?>',
colors: ['#91b224'],
is3D:true,
width:600,
height:550};
// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
first place, second place, and third place are the fields. CompName, compLvl, and danceName are the title.
EDIT picture of source code below
the chart values should be numbers instead of strings...
try removing the quotes...
from...
$first = '.$chartrow["firstpl_score1"].';
$second = '.$chartrow["2ndpl_score1"].';
$third = '.$chartrow["3rdpl_score1"].';
to...
$first = $chartrow["firstpl_score1"];
$second = $chartrow["2ndpl_score1"];
$third = $chartrow["3rdpl_score1"];

Google visualization world map

I'm trying to retrieve results using json in order to display world map with country list.
This is what I got so far:
function drawRegionsMap() {
$.ajax({
url: 'getlist.php",
dataType: "json"
}).done(function(result) {
var data = google.visualization.arrayToDataTable(result);
var view = new google.visualization.DataView(data)
view.setColumns([0, 1])
var chart = new google.visualization.GeoChart(
document.getElementById('map'));
chart.draw(data, options);
var geochart = new google.visualization.GeoChart(
document.getElementById('map'));
var options = {
width: "auto",
height: "auto",
colorAxis: {
colors: ['#E4B6D3', '#E06D94']
} // Map Colors
};
geochart.draw(data, options);
});
};
google.load('visualization', '1', {
'packages': ['geochart']
});
google.setOnLoadCallback(drawRegionsMap);
result returned from getlist.php is in json format:
{
"Country":[
"Germany",
"United States",
"Brazil",
"France",
"RU"
],
"Hits":[
200,
300,
400,
500,
600,
700
]
}
php code:
$data = array();
$data['Country'] = array();
$data['Hits'] = array();
$country = array('Germany','United States','Brazil','France','RU');
$hits = array(200,300,400,500,600,700);
for ($i = 0; $i < 6; $i++){
$data['Country'] = $country;
$data['Hits'] = $hits;
}
echo json_encode($data);
Looking in firebug console, I'm always getting : Error: Not an array
I've been trying to solve this puzzle for hours, but no success.
The returned result is an object, not an array.
The expected array would be:
[
["Country","Hits"],
["Germany",200],
["United States",300],
["Brazil",400],
["France",500],
["RU",600]
]
Modified PHP-code that returns this array:
<?php
$data = array(['Country','Hits']);
$country = array('Germany','United States','Brazil','France','RU');
$hits = array(200,300,400,500,600,700);
foreach ($country as $k => $v){
$data[] = array($v,$hits[$k]);
}
echo json_encode($data);
?>

Google Charts from MySQL JSON Encoded Array

I'm having one heck of a time here, how can I draw up the chart from a json_encoded mySQL array?
Data Retrieval (simply associated array from a PDO query):
if($cCt > 0){
header('Content-Type:application/json');
$table['cols'] = array(
array('id'=>'Date', 'label'=>'Date', 'type'=>'string'),
array('id'=>'Carbs', 'label'=>'Carbs', 'type'=>'number'),
array('id'=>'Sugar', 'label'=>'Sugar', 'type'=>'number'),
array('id'=>'Units', 'label'=>'Units', 'type'=>'number'));
for($i=0; $i<$cCt; ++$i){
$W = (isset($_GET['which'])) ? (int)$_GET['which'] : 0;
switch($W){
case 1: // weekly
case 2: // monthly
case 3: // yearly
$date = date('m/d', strtotime($CNums[$i]['Date']));
break;
case 4: // daily
$date = date('m/d g:i a', strtotime($CNums[$i]['Date']));
break;
default:
$date = date('m/d g:i a', strtotime($CNums[$i]['Date']));
break;
}
$rows[] = array('c'=>array('v'=>$date, 'v'=>$CNums[$i]['Carbs'], 'v'=>$CNums[$i]['Sugar'], 'v'=>$CNums[$i]['Units']));
}
$table['rows'] = $rows;
echo json_encode($table, JSON_NUMERIC_CHECK);
}else{
echo ErrorBox('Please login to see your charts.');
}
Code Attempt:
<script type="text/javascript">
google.load('visualization', '1.0', {'packages':['corechart']});
google.setOnLoadCallback(drawChart);
function drawChart() {
var $dUrl = "/assets/php/charts/chart.data.php?_=<?php echo time(); ?>&which=<?php echo (isset($which)) ? $which : 4; ?>&d=<?php echo (isset($d)) ? $d : null; ?>&dl=<?php echo (isset($dl)) ? $dl : null; ?>";
jQuery.getJSON($dUrl, function(d){
// Create a new blank DataTable
var data = new google.visualization.DataTable(d);
// Create our columns
/*
data.addColumn('date', 'Date');
data.addColumn('number', 'Carbs');
data.addColumn('number', 'Sugar');
data.addColumn('number', 'Units');
// Create our Rows
jQuery.each(d, function(i) {
data.addRows([d[i].Dates, d[i].Carbs, d[i].Sugar, d[i].Units]);
});
*/
var options = {
'colors': ['red', 'blue', 'yellow'],
'width': '98%',
'height': 280,
'backgroundColor': 'none',
'hAxis': {'textStyle': {fontName: 'Calibri',
fontSize: '12'}},
'vAxis': {'textStyle': {fontName: 'Calibri',
fontSize: '12'}},
'legendTextStyle': {fontName: 'Calibri',
fontSize: '12'}
};
//var chart = new google.visualization.ColumnChart(document.getElementById('<?php echo $where; ?>'));
var chart = new google.visualization.ColumnChart(document.getElementById('weekly_chart_div'));
chart.draw(data, options);
}).fail(function(msg){console.log('Error pulling in the data.' + msg);});
}
</script>
Original JSON from the $dUrl:
{"cols":[{"id":"Date","label":"Date","type":"string"},
{"id":"Carbs","label":"Carbs","type":"string"},
{"id":"Sugar","label":"Sugar","type":"string"},
{"id":"Units","label":"Units","type":"string"}],
"rows":[["08\/23","40.0000000","256.0000000","9.0000000"],
["08\/24","33.8333333","102.5000000","4.6666667"],
["08\/25","38.2000000","290.2000000","10.6000000"],
["08\/26","36.0000000","322.0000000","12.0000000"],
["08\/28","23.6666667","348.3333333","9.6666667"],
["08\/29","31.3333333","214.1666667","7.3333333"],
["08\/30","16.0000000","154.0000000","4.0000000"]]}
New JSON after Data Retrieval Update:
{"cols":[{"id":"Date","label":"Date","type":"string"},
{"id":"Carbs","label":"Carbs","type":"number"},
{"id":"Sugar","label":"Sugar","type":"number"},
{"id":"Units","label":"Units","type":"number"}],
"rows":[{"c":{"v":9}},{"c":{"v":4.6666667}},{"c":{"v":10.6}},{"c":{"v":12}},{"c":{"v":9.6666667}},{"c":{"v":7.3333333}},{"c":{"v":4}}]}
Yes, right now I am getting an error this.J[a].c is undefined, but it only shows where the chart should be loaded...not in FireBug
What I am aiming for is something like this:
example: http://o7th.com/Image3.png
Your rows are not formatted correctly. Rows is an array of objects, where each object has a "c" (array of cells) and an optional "p" (properties object) parameters. The array of cells is an array of objects with "v" (column data type, value of cell) and optional "f" (string, formatted value of cell) and "p" (parameters object) properties.
As an example, your first row of data should look like this:
{"c":[{"v":"08\/23"},{"v":40,"f":"40.0000000"},{"v":256,"f":"256.0000000"},{"v":9,"f":"9.0000000"}]}
In order to generate that from a JSON encoded PHP array, the array would have to look like this:
$row = array(
'c' => array(
array('v' => '08\/23'),
array('v' => 40, 'f' => "40.0000000"),
array('v' => 256, 'f' => "256.0000000"),
array('v' => 9, 'f' => "9.0000000")
)
);
By default, MySQL outputs all numbers as strings, so you need to cast them as ints or floats in order for them to be output as numbers, like this:
$foo = '33.333333'; // $foo == '33.333333'
$bar = (int) $foo; // $bar == 33
$cad = (float) $foo; // $cad == 33.333333
You can change or remove the formatted values if you don't want them (they are what will appear in the tooltips of the chart).
Edit:
You need to give each cell it's own array in the cells array; try this:
$rows[] = array(
'c'=>array(
array('v'=>$date),
array('v'=>$CNums[$i]['Carbs']),
array('v'=>$CNums[$i]['Sugar']),
array('v'=>$CNums[$i]['Units'])
)
);

How to populate Google chart API dynamically

I am trying to create a Google line chart using their API and JSON.
Hard coded, this chart works:
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Date', 'Sales'],
['Jun 25', 12.25],
['Jun 26', 8.00],
['Jun 27', 20.50]
['Jun 28', 12.75]
]);
var options = {
};
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
However, trying to populate it using JSON, I can not get this to work:
<?php
$data = array();
$data["Date"] = "Sales";
$data["Jun 25"] = "12.25";
$data["Jun 26"] = "8.00";
$data["Jun 27"] = "20.50";
$data["Jun 28"] = "12.75";
$data = json_encode($data);
?>
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable(<?php echo $data; ?>);
var options = {
};
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
I'm obviously not encoding the array correctly. Google has an example page on how to populate their charts with JSON data here: https://developers.google.com/chart/interactive/docs/php_example
However, I could not find any examples for how to setup the JSON data with a simple line chart like this.
You're close.
$data = array(
array('Date', 'Sales'),
array('June 25', 12.25),
array('June 26', 8.00)
);
json_encode($data);
Output
[["Date","Sales"],["June 25",12.25],["June 26",8]]
See it in action.
Josh has already provided the correct answer. But in case you want to use google.visualization.DataTable instead of google.visualization.arrayToDataTable, first you can add columns separately then add json encoded php array:
var data = new google.visualization.DataTable();
data.addColumn('string', 'Date');
data.addColumn('string', 'Sales');
data.addRows(<?php echo $data; ?>);
while($fetch = sqlsrv_fetch_array( $result, SQLSRV_FETCH_BOTH))
{
$grid[$count]= $fetch['Hour'];
$grid1[$count]=$fetch['Revenue'];
$data[$count]=array($fetch['Hour'],$fetch['Revenue']);
$count++;
}
$num=$count;
$data[0] = array('Hours','Revenue');
for ($i=0; $i<($num+1); $i++)
{
$data[$i]=(array('c' => array(array('v' => (string)$grid[$i]), array('v' =>(int)($grid1[$i]) ), ) ));
}
$sample=array(array('type' => 'string', 'label' => 'date'),array('type' => 'number', 'label' => 'Amount'));
$table['cols'] = $sample;
$table['rows'] = $data;
echo (json_encode($table ));
This worked for me,If You format your json like this it will definitely work

PHP: How to pass multiple variables to an array?

In the google chart api, the data for the chart is set by this line:
data.addRows([
['2004', 1000, 400],
['2005', 1170, 460],
['2006', 860, 580],
['2007', 1030, 540]
]);
I want to be able to set this data from data in my database. Below is an image of my database:
I want to take all values of salePrice and unitPrice and display the values on a line chart that corresponds to the period they were created.
Here is my code:
<?php
include("getteam.php");
$saleprice = mysql_query("
SELECT `outputValue` FROM `output` WHERE `teamID` = '$teamID' && `outputType` = 'salePrice'
")or die($saleprice."<br/><br/>".mysql_error());
// set ID's = to a variable and now get Outputs for each variable(teamID)
$salepriceNumR = mysql_num_rows($saleprice);
$sPrice = array();
$i="0";
while ($i<$salepriceNumR && $row = mysql_fetch_assoc($saleprice))
{
$sPrice[$i] = $row['outputValue'];
$i++;
}
$unitprice = mysql_query("
SELECT `outputValue` FROM `output` WHERE `teamID` = '$teamID' && `outputType` = 'unitPrice'
")or die($unitprice."<br/><br/>".mysql_error());
// set ID's = to a variable and now get Outputs for each variable(teamID)
$unitpriceNumR = mysql_num_rows($unitprice);
$uPrice = array();
$i="0";
while ($i<$unitpriceNumR && $row = mysql_fetch_assoc($unitprice))
{
$uPrice[$i] = $row['outputValue'];
$i++;
}
$chartrow = array();
for ($i = 0; $i < $unitpriceNumR; $i++ )
{
$chartrow[$i] = "['".$i."',".$sPrice[$i].", ".$uPrice[$i]."]";
}
switch ($currentStage) {
case "0":
case "1":
$value = $chartrow[0];
break;
case "2":
$value = $chartrow[0].",".$chartrow[1];
break;
case "3":
$value = $chartrow[0].",".$chartrow[1].",".$chartrow[2];
break;
default:
$value = $chartrow[0];
// You should have some default value, seriously!!!
}
?>
<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', 'Sales');
data.addColumn('number', 'Expenses');
data.addRows(JSON.parse( [<?php echo json_encode($value); ?>] ));
var options = {
width: 400, height: 240,
title: 'Company Performance'
};
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
<div id="chart_div"></div>
The problem is the way I am setting $value it is a string and so the data is not outputted correctly. Is there a way I can set $value so I can use it as intended?
When $value is echoed ($currentStage being the value 3) this is outputted:
['0',0, 0],['1',65, 35],['2',88, 35]
However when I view source I am getting:
data.addRows(JSON.parse( ["['0',0, 0],['1',65, 35],['2',88, 35]"] ));
I need to get rid of the "".
You have to parse your JSON string :
data.addRows(JSON.parse( <?php echo json_encode($value); ?> ));
If I'm not mistaken that should solve your problem.
Edit In fact I'm not sure I understand why you're setting you $value variable to a string; the whole point of json_encode being that you can directly encode objects or arrays.
Edit 2 : Here's how I see it, but my php is more than rusty.
<?php
$chartrow = array();
for ($i = 0; $i < $unitpriceNumR; $i++ )
{
$chartrow[$i] = array( (string)$i, (int)$sPrice[$i], (int)$uPrice[$i] );
}
switch ($currentStage) {
case "0":
case "1":
$value = $chartrow[0];
break;
case "2":
$value = array($chartrow[0], $chartrow[1]);
break;
case "3":
$value = array($chartrow[0], $chartrow[1], $chartrow[2]);
break;
default:
$value = $chartrow[0];
}
Edit 3 I edited the js snippet, I don't know why I left the brackets around the php tags.
Edit 4 Edited the php code to the working version.

Categories