unable to generate pie chart from phpmyadmin - javascript

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>

Related

while loop using google charts

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>

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.

Google pie chart single value from table

I have a problem to display a pie chart.
i have this code:
<?php
$con=mysql_connect("localhost","root","") or die("Failed to connect with database!!!!");
mysql_select_db("oes", $con);
// The Chart table contains two fields: weekly_task and percentage
// This example will display a pie chart. If you need other charts such as a Bar chart,
// you will need to modify the code a little to make it work with bar chart and other charts
$sth = mysql_query("select t.testname as Test,t.testdesc as `Tip test`,
DATE_FORMAT(st.starttime,'%d %M %Y ') as Data,
sub.subname as Disciplina,sub.subdesc as Profesor,sub.an as `Anul de studii`,
(SELECT sum(q.marks) from studentquestion as sq,
question as q where sq.testid=q.testid and sq.qnid=q.qnid and sq.answered='answered'
and sq.stdanswer=q.correctanswer and
sq.stdid='" . htmlspecialchars($_SESSION['stdid'],ENT_QUOTES) . "' and
sq.testid=t.testid) as Nota,(SELECT sum(q.marks)
from studentquestion as sq, question as q where sq.testid=q.testid
and sq.qnid=q.qnid and
sq.stdid='" . htmlspecialchars($_SESSION['stdid'],ENT_QUOTES) . "'
and sq.testid=t.testid) as NotaMaxima
from studenttest as st,test as t,subject as sub,student as ss where
t.testid=st.testid and st.stdid=".$_SESSION['stdid']."
and st.status='over' and sub.subid=t.subid and ss.stdid=".$_SESSION['stdid']."
order by t.testid DESC LIMIT 1 ;");
$rows = array();
//flag is not needed
$flag = true;
$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 column title
array('label' => 'Test', 'type' => 'string'),
array('label' => 'Nota', 'type' => 'number'),
);
$rows = array();
while($r = mysql_fetch_assoc($sth)) {
$temp = array();
// the following line will be used to slice the Pie chart
$temp[] = array('v' => (string) $r['Test']);
// Values of each slice
$temp[] = array('v' => (float) (($r['Nota']/$r['NotaMaxima'])*100) );
$rows[] = array('c' => $temp);
}
$table['rows'] = $rows;
$jsonTable = json_encode($table);
//echo $jsonTable;
?>
<html>
<head>
<link rel="stylesheet" type="text/css" href="../../stil/stil.css"/>
<!--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);
function drawChart() {
// Create our data table out of JSON data loaded from server.
var data = new google.visualization.DataTable(<?=$jsonTable?>);
var options = {
title: 'Procentaj de raspuns',
is3D: 'true',
backgroundColor: "transparent",
width: 500,
height: 300,
max:10,
};
// 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(data, options);
}
</script>
</head>
<body>
<!--this is the div that will hold the pie chart-->
<br><br><br><br><br><br><div id="chart_div" style="padding-left: 240px; align:center;"></div></>
</body>
</html>
I want to display this value: http://i.stack.imgur.com/1a2zm.png
Not like this: http://i.stack.imgur.com/bVcJE.png
But like real percentage. Ex: 54% one color and the rest other color. I dont know how to do it because is a single value.
In sql select the value is " NotaMaxima "
And how do i use $rows for 2 things like Nota and NotaMaxima?
U can add by your self another value (other).
If $result array:
Ex. if(count($result)==1) then $anotherVal = 100-$result[0] and add to $result[1]=$anotherVal.
And add to chart data two values.

Error in response to storage.get: TypeError: Cannot read property 'style' of null

I am trying to get data from an oracle database into an LineChart using GoogleCharts but I am always confronted with some errors.
If someone could help me, it'd be greatly appreciated !
Here is the script in order to get the line chart :
<html>
<head>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript">
$( document ).ready(function() {
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart (callback) {
var jsonData = $.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
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);
//PieCharts expects 2 columns of data: a label and a value, so we need to use a DataView to restrict to 2 columns
var view = new google.visualization.DataView(data);
view.setColumns([0, 1]);
var options = {
title: 'Whatever'
};
//Instantiate and draw our chart, passing in some options
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
});
</script>
</head>
<body>
<!--Div that will hold the pie chart-->
<div id="chart_div">Test</div>
</body>
And here is the Phpscript to get the data into a table :
<?php
//On exécute la requete
//on appelle la page connexion
include 'connexion.php';
//La requete
$query = "
select A.*
from (
SELECT
EB_RESULTAT_DTM.VALEUR AS EB_RESULTAT_VALEUR,
EB_RESULTAT_DTM.INSERT_DATE AS EB_RESULTAT_INSERT_DATE,
rank() over (partition by EB_INDICATEUR_DTM.INDICATEUR_NUM,to_char(EB_RESULTAT_DTM.INSERT_DATE,'yyyymm') order by to_char(EB_RESULTAT_DTM.INSERT_DATE,'yyyymmdd') asc) as rang,
to_char(EB_RESULTAT_DTM.INSERT_DATE,'yyyymm') as MOIS_M
FROM COMPTEUR_OWNER.EB_DOMAINE_DTM EB_DOMAINE_DTM
INNER JOIN
COMPTEUR_OWNER.EB_INDICATEUR_DTM EB_INDICATEUR_DTM
ON EB_DOMAINE_DTM.EB_DOMAINE_DTM_NUM =
EB_INDICATEUR_DTM.X_EB_DOMAINE_DTM_NUM
INNER JOIN
COMPTEUR_OWNER.EB_RESULTAT_DTM EB_RESULTAT_DTM
ON EB_INDICATEUR_DTM.INDICATEUR_NUM =
EB_RESULTAT_DTM.X_EB_INDICATEUR_DTM_NUM
WHERE EB_INDICATEUR_DTM.INDICATEUR_NUM = 106
AND EB_RESULTAT_DTM.INSERT_DATE BETWEEN ADD_MONTHS (SYSDATE, -9)
AND SYSDATE
) a where a.rang=1
";
$stid = oci_parse($conn, $query);
oci_execute($stid);
$table = array();
$table['cols'] = array(
/* define your DataTable columns here
* each column gets its own array
* syntax of the arrays is:
* label => column label
* type => data type of column (string, number, date, datetime, boolean)
*/
array('label' => 'Nombres', 'type' => 'number'),
array('label' => 'Date', 'type' => 'date'),
// etc...
);
$rows = array();
while($r = oci_fetch_assoc($stid)) {
$temp = array();
// each column needs to have data inserted via the $temp array
$temp[] = array('v' => $r['EB_RESULTAT_VALEUR']);
$temp[] = array('v' => $r['EB_RESULTAT_INSERT_DATE']);
// etc...
// insert the temp array into $rows
$rows[] = array('c' => $temp);
}
// populate the table with rows of data
$table['rows'] = $rows;
// encode the table as JSON
$jsonTable = json_encode($table);
// return the JSON data
echo $jsonTable;
?>
I ever get this message :
Error in response to storage.get: TypeError: Cannot read property 'style' of null
Or :
undefined is not a function
There are a few errors I can see. First, you are parsing the wrong object in the arrayToDataTable method:
var data = google.visualization.arrayToDataTable($.parseJSON(drawChart));
should be:
var data = google.visualization.arrayToDataTable($.parseJSON(jsonData));
Then, your columns are in the wrong order. The LineCharts expect the x-axis values (your dates) to be the first column, then the y-values in the second column. Also, you need to output your numbers as numbers instead of strings; just add JSON_NUMERIC_CHECK to the json_encode function call:
echo json_encode($rows, JSON_NUMERIC_CHECK);
So i've changed both of the PHP and script but now get another error message :
Uncaught Error: Not an array
Here is the php getData2.php :
<?php
include 'connexion.php';
//
$sql = oci_parse($conn, "select A.*
from (
SELECT
EB_RESULTAT_DTM.VALEUR AS EB_RESULTAT_VALEUR,
EB_RESULTAT_DTM.INSERT_DATE AS EB_RESULTAT_INSERT_DATE,
rank() over (partition by EB_INDICATEUR_DTM.INDICATEUR_NUM,to_char(EB_RESULTAT_DTM.INSERT_DATE,'yyyymm') order by to_char(EB_RESULTAT_DTM.INSERT_DATE,'yyyymmdd') asc) as rang,
to_char(EB_RESULTAT_DTM.INSERT_DATE,'yyyymm') as MOIS_M
FROM COMPTEUR_OWNER.EB_DOMAINE_DTM EB_DOMAINE_DTM
INNER JOIN
COMPTEUR_OWNER.EB_INDICATEUR_DTM EB_INDICATEUR_DTM
ON EB_DOMAINE_DTM.EB_DOMAINE_DTM_NUM =
EB_INDICATEUR_DTM.X_EB_DOMAINE_DTM_NUM
INNER JOIN
COMPTEUR_OWNER.EB_RESULTAT_DTM EB_RESULTAT_DTM
ON EB_INDICATEUR_DTM.INDICATEUR_NUM =
EB_RESULTAT_DTM.X_EB_INDICATEUR_DTM_NUM
WHERE EB_INDICATEUR_DTM.INDICATEUR_NUM = 106
AND EB_RESULTAT_DTM.INSERT_DATE BETWEEN ADD_MONTHS (SYSDATE, -9)
AND SYSDATE
) a where a.rang=1");
oci_execute($sql);
//while (($row = oci_fetch_array($sql, OCI_BOTH)) != false) {
// Utilisez des noms de colonne en majuscule pour les indices des tableau associatif
// echo $row['EB_RESULTAT_VALEUR'];
// echo $row['EB_RESULTAT_INSERT_DATE'];
//}
//json_encode($row);
$rows = Array();
while($row = oci_fetch_array($sql, OCI_BOTH)){
array_push($rows, $row[0], $row[1]);
}
echo json_encode($rows);
oci_free_statement($sql);
oci_close($conn);
?>
It returns this :
["9415094","14\/09\/13 14:39:56,000000","9419954","02\/11\/13 13:25:26,000000","9355868","07\/12\/13 13:25:58,000000","9369691","04\/01\/14 13:24:19,000000","9385231","01\/02\/14 13:26:36,000000","9414700","01\/03\/14 13:26:28,000000"]
And here is the index_4.php (script) :
<html>
<head>
<title>Donné volumétrique</title>
<!-- Load jQuery -->
<script language="javascript" type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js">
</script>
<!-- Load Google JSAPI -->
<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 jsonData = $.ajax({
url: "getData2.php",
dataType: "json",
async: false
}).responseText;
var data = google.visualization.arrayToDataTable($.parseJSON(drawChart));
var options = {
title: 'Donnée Volumétrique'
};
var chart = new google.visualization.LineChart(
document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
</head>
<body>
<div id="chart_div" style="width: 900px; height: 500px;">
</div>
</body>
</html>
And here's what I get :
http://imgur.com/w8jexhJ "Error message"
EDIT 1 : $rows = Array(); to $rows = Array(array('Nombres', 'Date'));
AND
array_push($rows, $row[0], $row[1]); to array_push($rows, array($row[0], $row[1]));
Getting : [["Nombres","Date"],["9419954","02\/11\/13 13:25:26,000000"],["9355868","07\/12\/13 13:25:58,000000"],["9369691","04\/01\/14 13:24:19,000000"],["9385231","01\/02\/14 13:26:36,000000"],["9414700","01\/03\/14 13:26:28,000000"]]

Passing an array to Google Charts API via AJAX

I can grab the number of users who signed up a specific date by using:
$query = "SELECT COUNT(*), DATE(FROM_UNIXTIME(time)) as date
FROM user GROUP BY DATE(FROM_UNIXTIME(time))";
Google Charts supplies the following JS function for drawing the graph
function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Day');
data.addColumn('number', 'Users');
data.addRows([
['03-22-2012', 1000],
['03-23-2011', 1170]
]);
var options = {
title: 'Signups'
};
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
How do I use my database query with data.addRows via ajax? Im stuck here..help is appreciated!
Thanks
Here solved by using a test table stackoverflow with one row, test_ (a timestamp) to mimick what you describe above :
time_
-------------------
2013-07-07 13:23:31
2013-07-07 13:23:44
2013-07-09 13:23:50
2013-07-08 13:23:57
2013-07-09 13:24:07
2013-07-09 13:24:14
googlechart.php, which output will be fetched through AJAX :
<?
mysql_connect('localhost','root','xxx');
mysql_select_db('test');
$SQL='SELECT COUNT(*) as c, DATE(time_) as date FROM stackoverflow GROUP BY DATE(time_)';
$result=mysql_query($SQL);
$a = array();
$a['cols'][] = array('type' => 'string', 'label' => 'Day');
$a['cols'][] = array('type' => 'number', 'label' => 'Users');
while($row = mysql_fetch_assoc($result)) {
$a['rows'][]['c']=array(
array('v' => $row['date']),
array('v' => $row['c'])
);
}
echo json_encode($a);
?>
googlechart.html (actual page) using jQuery AJAX and produces a google chart as described above :
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">google.load('visualization', '1.0', {'packages':['corechart']});</script>
<script type="text/javascript">
function drawChart(json) {
var data = new google.visualization.DataTable(json);
var options = {
title: 'Signups'
};
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
$(document).ready(function() {
$.ajax({
url: 'googlechart.php',
success : function(json) {
drawChart(json);
}
});
});
</script>
<div id="chart_div" style="width:500px;height:400px;"></div>
result :

Categories

Resources