while loop using google charts - javascript

So im having this issue, im pulling numbers from a database, for hits on a page. The pie chart worked fine when there was only one country in the database, now theres a few, but it grabs from the top 5. It worked fine but i think my while loop is screwed up, how would i reformat it so it works?`
Database query:
$csel = $odb->query("SELECT country, COUNT(*) AS cnt FROM bots GROUP BY country ORDER BY cnt DESC LIMIT 5");
display:
<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([
['Country', 'Total Bots'],
<?php
while ($c = $csel->fetch())
{
$top2 = geoip_country_name_by_id($gi, $c[0]);
$top = number_format($c[1]);
echo ("['$top2', '$top']");
}
I figured it was because i didnt have a comma at the end of the echo, so i tried that and the pie chart was grey and said "other"
I think i need to somehow make a string that does what the echo says, and adds a comma until the last piece of data.
Can someone help me fix this?

<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([
['time', 'Price'],
<?php while ($r = mysqli_fetch_array($res)) {
echo "[' ".$r["timestamp"]." ', ".$r["totalprice"]." ],";
} ?>
]);
var options = {
title: 'My Daily Activities'
};
var chart = new google.visualization.PieChart(document.getElementById('piechart'));
chart.draw(data, options);
}
</script>

Related

Dynamic google line chart not showing up with php and Javascript

I am using google charts to display a line graph on my locally hosted web page. I am using mysqli to take the data from my phpmyadmin database then echoing this into the row spaces in the javascript.
This is the code within my html body:
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>
<script>
google.charts.load('current', {packages: ['corechart', 'line']});
google.charts.setOnLoadCallback(drawBasic);
function drawBasic() {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Date');
data.addColumn('number', 'Speed');
data.addRows([
<?php
$sql = "SELECT id_rides, speed, date_completed FROM rides_done WHERE (id_users = $_SESSION[id])";
$result = mysqli_query($link, $sql);
while($row = mysqli_fetch_assoc($result)) {
$date = $row['date_completed'];
$speed = floatval($row['speed']);
echo "['".$date."', ".$speed."],";
}
?>
]);
var options = {
hAxis: {
title: 'Ride date'
},
vAxis: {
title: 'Average speed'
}
};
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
The problem is that nothing is being displayed on the web page.
I know that the query works as I tried this on it's own outside of the javascript and this was output: results of sql query
Before I added the dynamic element of the chart it was working fine with just random lists of data.
I was expecting to see a line graph with 'Average Speed' on the y-axis and 'Ride date' on the x-axis with 7 datapoints but nothing was displayed.
It seems that js is particular about datatypes here so I'm wondering if it is something to do with either of the following lines - both of which I have been fiddling around with to no avail.
echo "['".$date."', ".$speed."],";
data.addColumn('string', 'Date');
data.addColumn('number', 'Speed');
Thank you very much. All suggestions and ideas are very welcome. As is probably evident I am very new to Javascript so likely to be making some stupid mistakes.
A couple of things I would say: As you appear to wish to use a date within the dataTable perhaps setting that as a date type column would be better and casting the value from the db query as a date using new Date(str). I'd also suggest that you use json_encode once you have run the db query to create a JSON object rather than manually building a string as you do above - one downside to that approach is the trailing comma which might cause issues.
I rattle together a working demo using bogus data from my db to emulate what you were trying to do here. The SQL query uses aliases to take arbitrary data and name it as you do so the Javascript remains fairly much the same.
With the JSON data it is easy to iterate through the Object using Object.keys( json ).forEach() type structure ( I apologise if this is new to you )
<?php
#add a db connection
chdir('../../dbo');
require 'db-conn-details.php';
require 'mysqli-conn.php';
?>
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='utf-8' />
<script src='//www.gstatic.com/charts/loader.js'></script>
<script></script>
<title>Google charts.....</title>
<style>
#chart_div{
width:800px;height:600px
}
</style>
</head>
<body>
<div id='chart_div'></div>
<script>
<?php
$sql = 'SELECT `speed`, `date_completed` FROM `rides_done` WHERE ( `id_users` = $_SESSION[id] )';
$sql = 'select `dr` as `speed`, date(`lasteditdate`) as `date_completed` from `testtable` limit 20'; # example sql...
$result = $link->query( $sql );
$json = json_encode( $result->fetch_all( MYSQLI_ASSOC ) );
printf('const json=%s;', $json );
?>
google.charts.load('current', { packages: ['corechart'] } );
google.charts.setOnLoadCallback( drawBasic );
function drawBasic() {
var data = new google.visualization.DataTable();
data.addColumn('date', 'Date');
data.addColumn('number', 'Speed');
Object.keys( json ).forEach( key=>{
let obj=json[ key ];
data.addRow( [ new Date( obj.date_completed ), parseFloat( obj.speed ) ] );
})
var options = {
hAxis: {
title: 'Ride date'
},
vAxis: {
title: 'Average speed'
}
};
var chart = new google.visualization.LineChart( document.getElementById('chart_div') );
chart.draw( data, options );
}
</script>
</body>
</html>
The above yielded a chart like this:

Google charts php mysql and ajax

Trying with all my best but I just can't figure this out...
I want a user to search a genename in a database. Then update a google bubble chart with the new genename data. Documentation: [https://developers.google.com/chart/interactive/docs/gallery/bubblechart][1]
I already implanted the ajax part. So updating the bubble chart with new data after a search is what has to be done somehow....
HTML
<html>
<head>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript">
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawSeriesChart);
function drawSeriesChart() {
var jsonData = $.ajax({
url: "getData.php",
dataType: "json",
async: false
}).responseText;
var data = google.visualization.arrayToDataTable(jsonData);
var chart = new google.visualization.BubbleChart(document.getElementById('series_chart_div'));
chart.draw(data, options);
}
var options = {
title: 'random title',
hAxis: {title: 'horizontal axis'},
vAxis: {title: 'vertical axis'},
bubble: {textStyle: {fontSize: 11}}
};
}
</script>
</head>
<body>
<form action="getData.php" method="post">
Genename:<input type="text" name="gene" value=""><br>
<input type="submit" value="Submit">
</form>
<div id="series_chart_div" style="width: 900px; height: 500px;"></div>
</body>
</html>
PHP
<?php
$search_value=$_POST["gene"];
$mysqli = new mysqli('localhost','root','usbw','mydb');
$myArray = array();
if ($result = $mysqli->query("SELECT * FROM transcriptome WHERE genename LIKE '%$search_value%'")) {
while($row = $result->fetch_row()) {
$myArray[] = $row;
} //json encode and return to chart.
//this is how the data looks like hardcoded without the ajax part "['".$row['genename']."', 2, ".$row['TA11MEAN'].", 'control', ".$row['TA11STD']."],";
//2 is position on x-axis + control is groupname
}
$result->close();
$mysqli->close();
?>
Many thanks in advance :)

unable to generate pie chart from phpmyadmin

i want to create google pie chart with help of getting table from database ...but till now i did not get output ...i have searched several websites..but i did not clarify anything...please check my code and tell
<?php
mysql_connect('localhost','root','');
mysql_select_db('chart');
$sqlquery1="select * from pie_chart";
$sqlresult1=mysql_query($sqlquery1);
$rows=array();
while($r=mysql_fetch_assoc($sqlresult1))
{
$rows[]=$r;
}
$data= json_encode($rows);
?>
<html>
<head>
<!--Load the AJAX API -->
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js" type="text/javascript"></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 data = new google.visualization.DataTable();
data.addColumn("string", "Quarter");
data.addColumn("number", "Number");
data.addRows(<?php echo $data ?>);
]);
//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>
<?php
/* Establish the database connection */
$mysql =mysqli_connect('localhost', 'root', '', 'chart');
/* select all the tasks from the table piechart */
$result = $mysql->query('SELECT * FROM piechart');
/*
---------------------------
example data: Table (piechart)
--------------------------
Task percent
job 30
daily 20
working 35
sleep 15
*/
$rows = array();
$table = array();
$table['cols'] = array(
// Labels for your chart, these represent the column titles.
/*
note that one column is in "string" format and another one is in "number" format
as pie chart only required "numbers" for calculating percentage
and string will be used for Slice title
*/
array('label' => 'task', 'type' => 'string'),
array('label' => 'percent', 'type' => 'number')
);
/* Extract the information from $result */
/* associate array are used in above ,so we used foreach loop*/
foreach($result as $r)
{
$temp = array();
// The following line will be used to slice the Pie chart
$temp[] = array('v' => (string) $r['task']);
// Values of the each slice
$temp[] = array('v' => (int) $r['percent']);
//rows of side title
$rows[] = array('c' => $temp);
}
$table['rows'] = $rows;
// convert data into JSON format
$jsonTable = json_encode($table);
//echo $jsonTable;
?>
<html>
<head>
<!--Load the Ajax API-->
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.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);
// Load the Visualization API and the piechart package.
function drawChart()
{
// Create our data table out of JSON data loaded from server.
var bar_chart_data = new google.visualization.DataTable(<?php echo $jsonTable; ?>);
var options = {
title: 'Daily Work log',
is3D: 'true',//3D effect true
width: 900,
height: 500
};
// Instantiate and draw our chart, passing in some options.
// Do not forget to check your div ID
var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
chart.draw(bar_chart_data, options);
}
</script>
</head>
<body>
<!--this is the div that will hold the pie chart-->
<div id="chart_div" ></div>
</body>
</html>
</script>
</head>

Use php variable in google pie chart

I want to use my PHP variable in Google chart,but the chart couldn't read my PHP tag. As you can see the code below I put my PHP variable in the script. (The PHP variable I have defined at top of the code and the result is correct). What's wrong with my code ? Is there any solution for this ? Do ask me for more information if needed. Thank you.
<script type="text/javascript">
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Order', 'Amount'],
['Completed', '<?php echo$completed ?>'],
['New', '<?php echo$new ?>']
]);
var options = {
title: 'Total Order ' + <?php echo$total; ?>
};
var chart = new google.visualization.PieChart(document.getElementById('piechart'));
chart.draw(data, options);
}
</script>
Working Example.
<?php
$completed = 50;
$new = 10;
$total = 30;
?>
<html>
<head>
<!--Load the AJAX API-->
<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([
['Order', 'Amount'],
['Completed', parseInt('<?php echo $completed; ?>')],
['New', parseInt('<?php echo $new; ?>')]
]);
var options = {
title: 'Total Order ' + <?php echo$total; ?>
};
var chart = new google.visualization.PieChart(document.getElementById('piechart'));
chart.draw(data, options);
}
</script>
</head>
<body>
<div id="piechart"></div>
</body>
</html>
According to docs, for Google visualization pie charts, there must be one datatype string column and one number column.
So you should parse the Amount column to integer or float before rendering the data. You can do it in php itself or in javascript as,
var data = google.visualization.arrayToDataTable([
['Order', 'Amount'],
['Completed', parseInt('<?php echo $completed; ?>')],
['New', parseInt('<?php echo $new; ?>')]
]);
var options = {
title: 'Total Order ' + parseInt('<?php echo $total; ?>')
};
You can also use javascript parseFloat() instead of parseInt() if your amount values containing decimal values.
<span id="json-genderby"><?php echo json_encode($arrayGenderGroupBy); ?></span>
<div id="piechart" style="width: 900px; height: 500px;"></div>
</body>
<script type="text/javascript">
$(window).on('load', function() {
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var json_gender = $("#json-genderby").text()
var arrayGenderBy = [];
var count = 0;
$.each(JSON.parse(json_gender), function(i, item) {
if (count == 0)
arrayGenderBy[count] = [item[0], item[1]];
else
arrayGenderBy[count] = [ item[0], parseInt(item[1]) ];
count ++
});
var data = google.visualization.arrayToDataTable(arrayGenderBy);
var options = { title: 'Servey Questions Answered by Gender' };
var chart = new google.visualization.PieChart(document.getElementById('piechart'));
chart.draw(data, options);
}
});
</script>
You can use scripts in PHP.
But, You can't use PHP in scripts.
It won't work.

Table has no columns - Google Charts - PHP AJAX

I started to learn how to use Google Charts today and I'm a bit stuck.
I have dynamic data (changes about 3-4 times a day) to pump into the chart (Pie Chart). I'm using AJAX as the data source and PHP as my backend.. I tried to do it this way but to no avail:
AJAX:
<?php
include $_SERVER['DOCUMENT_ROOT'].'/includes/galaxy-connect.php';
$database = new Connection();
$database = $database->Connect();
$statement = $database->Prepare(" SELECT COUNT(Membership_Level_Name) AS MemTotal, Membership_Level_Name
FROM membership AS M
LEFT JOIN membership_levels AS L
ON M.`Membership_Level_Id` = L.`Membership_Level_Id`
LEFT JOIN membership_status AS S
ON M.`MembershipStatusId` = S.MembershipStatusId
WHERE M.`MembershipStatusId` = 1
GROUP BY L.`Membership_Level_Name`
ORDER BY L.`Membership_Level_Id` ");
$statement->execute();
$MembershipTotals = $statement->fetchall(PDO::FETCH_ASSOC);
if (!empty($MembershipTotals)) {
foreach ($MembershipTotals as $MembershipTotal) {
$data[] = array(
"cols" => array("id"=>"Membership_Level_Name", "label"=>"Membership Level", "type"=>"varchar"),
array("id"=>"MemTotal", "label"=>"Total", "pattern"=>"", "type"=>"number"),
"rows" => array($MembershipTotal['Membership_Level_Name'], $MembershipTotal['MemTotal'])
);
}
}
echo json_encode($data);
so thats my ajax, and it produces:
(ok wont let me post an image but heres the results)
[{"cols":{"id":"Membership_Level_Name","label":"Membership Level","type":"varchar"},"0":{"id":"MemTotal","label":"Total","pattern":"","type":"number"},"rows":["Start Up","24"]},{"cols":{"id":"Membership_Level_Name","label":"Membership Level","type":"varchar"},"0":{"id":"MemTotal","label":"Total","pattern":"","type":"number"},"rows":["Member","131"]},{"cols":{"id":"Membership_Level_Name","label":"Membership Level","type":"varchar"},"0":{"id":"MemTotal","label":"Total","pattern":"","type":"number"},"rows":["Member Plus","170"]},{"cols":{"id":"Membership_Level_Name","label":"Membership Level","type":"varchar"},"0":{"id":"MemTotal","label":"Total","pattern":"","type":"number"},"rows":["Premier Member","31"]},{"cols":{"id":"Membership_Level_Name","label":"Membership Level","type":"varchar"},"0":{"id":"MemTotal","label":"Total","pattern":"","type":"number"},"rows":["Bronze","97"]},{"cols":{"id":"Membership_Level_Name","label":"Membership Level","type":"varchar"},"0":{"id":"MemTotal","label":"Total","pattern":"","type":"number"},"rows":["Silver","145"]},{"cols":{"id":"Membership_Level_Name","label":"Membership Level","type":"varchar"},"0":{"id":"MemTotal","label":"Total","pattern":"","type":"number"},"rows":["Gold","188"]},{"cols":{"id":"Membership_Level_Name","label":"Membership Level","type":"varchar"},"0":{"id":"MemTotal","label":"Total","pattern":"","type":"number"},"rows":["Affiliate","3"]},{"cols":{"id":"Membership_Level_Name","label":"Membership Level","type":"varchar"},"0":{"id":"MemTotal","label":"Total","pattern":"","type":"number"},"rows":["Charity\/Education","4"]}]
So the next step is to call that data, I took the code from Google Charts "Connecting to a database" (or something like that) page:
<script type="text/javascript" src="https://www.google.com/jsapi"></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: "/ajax/charts/membershiptotals.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>
Reload the web page and it produces the error:
Table has no columns
I don't understand why though.. I looked at other solutions and posted on Quora and the Google group for the API but to no avail.. could someone tell me whats wrong with the code??
I found the answer:
AJAX was changed to:
<?php
include $_SERVER['DOCUMENT_ROOT'].'/includes/galaxy-connect.php';
$database = new Connection();
$database = $database->Connect();
$statement = $database->Prepare(" SELECT COUNT(Membership_Level_Name) AS MemTotal, Membership_Level_Name
FROM membership AS M
LEFT JOIN membership_levels AS L
ON M.`Membership_Level_Id` = L.`Membership_Level_Id`
LEFT JOIN membership_status AS S
ON M.`MembershipStatusId` = S.MembershipStatusId
WHERE M.`MembershipStatusId` = 1
GROUP BY L.`Membership_Level_Name`
ORDER BY L.`Membership_Level_Id` ");
$statement->execute();
$MembershipTotals = $statement->fetchall(PDO::FETCH_OBJ);
$col1=array();
$col1["id"]="";
$col1["label"]="Membership Type";
$col1["pattern"]="";
$col1["type"]="string";
$col2=array();
$col2["id"]="";
$col2["label"]="Total";
$col2["pattern"]="";
$col2["type"]="number";
$cols = array($col1,$col2);
$rows=array();
foreach ($MembershipTotals AS $MembershipTotal) { //foreach ($Event->TrainingTotals['ConfirmedTotal'] AS $Key => $Value) {
$cell0["v"]=$MembershipTotal->Membership_Level_Name;
$cell1["v"]=intval($MembershipTotal->MemTotal);
$row0["c"]=array($cell0,$cell1);
array_push($rows, $row0);
}
$data=array("cols"=>$cols,"rows"=>$rows);
echo json_encode($data);
which made it a bit easier and then on the actual page:
<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: "/ajax/charts/membershiptotals.php",
dataType:"json",
async: false
}).responseText;
// Create our data table out of JSON data loaded from server.
var data = new google.visualization.DataTable(jsonData);
var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
chart.draw(data, {title:'Membership Bookings', width: 800, height: 500});
}
</script>
Basically I had to clearly declare the columns, and the intval is to turn it into a integer, otherwise it returns the number as a string which Google doesn't like.. hope this helps anyone :)
thanks to Harish for an answer but I needed it more dynamic :-)
this is the format of the array to be passed.
javascript:
var jsondata; //json data recived from php script
var data = google.visualization.arrayToDataTable(jsondata);
php:
$data = array(
array('Membership Level', 'MemTotal'),
array('Member Plus', 170),
array('Member', 131)
);
echo json_encode($data);
Your have to pass Json array not object.

Categories

Resources