Related
I have an admin page that contains several divs. And some divs contain google charts.
My charts are feeding from php+MySQL data.
Some divs(or chart) update 60 sec. Some divs(or chart) will be updated 1 hour.
So that different divs should update different period. (That's why I don't refresh whole page.
Anyway,When I refresh page there is no problem, but when I try to update my div, div updates, but there is nothing inside about graph.
Can you help me?
Here is my php code:
// QUERY AND PHP ARRAY FOR JSON
$query = "SELECT CONCAT(cdate,' ',chour,':00:00') AS ctime ,sum(bytesin*0.000002222) as totalKbpsin, sum(bytesout*0.000002222) as totalKbpsout FROM traffic_user_daily group by cdate,chour HAVING ctime >= now() - INTERVAL 1 DAY ";
$result = $conn->query($query);
$rows= array();
$table = array();
$table['cols'] = array(
array('label' => 'Tarih' , 'type' => 'string'),
array('label' => 'Inbound' , 'type' => 'number'),
array('label' => 'Outbound' , 'type' => 'number'),
);
foreach($result as $r) {
$temp = array();
$temp[] = array('v' => (string) substr($r['ctime'],11,5));
$temp[] = array('v' => (int) $r['totalKbpsin']);
$temp[] = array('v' => (int) $r['totalKbpsout']);
$rows[] = array('c' => $temp);
}
$table['rows'] = $rows;
$jsonTable = json_encode($table);
?>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
// CHART JAVA CODE
google.charts.load('visualization','current', {'packages':['corechart','bar'], 'language': 'en'});
// Draw the line chart is loaded.
google.setOnLoadCallback(drawBigChart);
// Callback that draws the line chart
function drawBigChart() {
var data = new google.visualization.DataTable(<?=$jsonTable?>);
var options = {
chartArea: {
'height': '80%',
left: "5%"
},
legend: {
position: 'right',
textStyle: {
color: '#bdbdbd',
fontSize: 12
}
},
hAxis: {
showTextEvery:2,
textStyle: {color: '#bdbdbd',
fontSize: 12,
},
baselineColor: '#bdbdbd',
gridlines: {color:'bdbdbd'},
},
vAxis: {
baselineColor: '#bdbdbd',
textStyle: {color:'#bdbdbd'},
gridlines: {color:'#bdbdbd' },
minValue: 0,
},
intervals: { 'style':'area' },
curveType: 'function',
crosshair: {orientation: 'vertical'},
animation: {
startup: true,
duration: 1000
},
};
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
<!-- OUTER DIV -->
<div class="col s12 m12">
<!-- CHART DIV -->
<div id="dash_big_chart" class="card">
<div class="card-content">
<div>
<span class="card-title grey-text lighten-1">
<?php echo $_SESSION['companyname'] ?></span></div>
<div id="chart_div">
</div></div></div></div>
<script type="text/javascript">
/// refresh script ////
setInterval(function(){
$("#dash_big_chart").load('big_chart.php')
},60000);
});
</script>
And then I have another php page named big_chart.php. That contains Query and array for JSON part , Graph java except google.charts.load and CHAR DIV.
Can you hep me?
jQuery load() wants to load HTML into a page element.
What you want to do is totally different:
You want to get json data via an ajax request, and then let googlecharts redraw the chart with that new data.
Therfor you have to add the json data as parameter to your drawBigChart function.
Code would look like this:
// For the first load you can pass the json data just like you did before.
google.setOnLoadCallback(function(){
drawBigChart(<?=$jsonTable?>);
});
function drawBigChart(json_data) {
// pass the parameter into the google charts DataTable
var data = new google.visualization.DataTable(json_data);
var options = {...}; // I left out the options here only to make the code more visible
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
// For the interval you retrieve the data via ajax request and pass
// it to the drawBigChart function
setInterval(function(){
$.getJSON( "big_chart.php", function( data ) {
drawBigChart(data);
});
},60000);
In your setInterval() you are replacing <div id="dash_big_chart"/> and everything inside it, including the <div id="chart_div"/> which is the area where Google is drawing the chart.
However, the code that actually draws the chart is up above, in the JavaScript, is the function drawBigChart(). And the data that gets drawn to the chart is
var data = new google.visualization.DataTable(<?=$jsonTable?>);
To accomplish what you want, you need to refactor. You don't need to download new HTML, you just need to download new data and update the chart.
Change the drawBigChart() method to take an argument which is the chart data, so you would call it like drawBigChart(jsonTable).
Once you can do that, instead of loading in HTML and replacing a div, as you are currently doing, you just need to load in new JSON data and call drawBigChart(newJsonTable) with the new data.
Something like
setInterval(function(){
$.ajax({
'url': 'get_new_data.php', // url should return only JSON data
'dataType': 'json',
'async': true
}).success(function(result) {
// Draw the chart again with the updated data
drawBigChart(result);
});
}, 60000); // 60 second refresh
I changed my page as you describe:
google.charts.load('visualization','current', {'packages': ['corechart','bar'], 'language': 'en'});
google.setOnLoadCallback(drawBigChart);
function drawBigChart(jsonTable) {
var data = new google.visualization.DataTable(<?=$jsonTable?>);
var options = { some visual thing};
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
And Interval script:
$(document).ready(function(){
$("#activeuserlist").on("click", "a.modal-trigger", function(){
$('#modalkes').openModal();
});
setInterval(function(){
$("#activeuserlist").load('activeuserlist2.php') //another DIV
$("#dash_kullanicisayisi").load('kullanicisayisi.php') //ANother DIV
$.ajax({
'url': 'get_new_data.php', // url should return only JSON data
'dataType': 'json',
'async': true
}).success(function(result) {
// Draw the chart again with the updated data
drawBigChart(result);
});
},60000);
});
And my get_new_data.php is like that:
<?php
require_once("inc/functions.php");
startSession();
connectDB($conn);
date_default_timezone_set('Europe/Istanbul');
mb_internal_encoding("UTF-8");
$now = date("Y-m-d H:m:s");
$query = "SELECT CONCAT(cdate,' ',chour,':00:00') AS ctime ,sum(bytesin*0.000002222) as totalKbpsin, sum(bytesout*0.000002222) as totalKbpsout FROM traffic_user_daily group by cdate,chour HAVING ctime >= now() - INTERVAL 1 DAY ";
$result = $conn->query($query);
$rows= array();
$table = array();
$table['cols'] = array(
array('label' => 'Tarih' , 'type' => 'string'),
array('label' => 'Inbound' , 'type' => 'number'),
array('label' => 'Outbound' , 'type' => 'number'),
);
foreach($result as $r) {
$temp = array();
$temp[] = array('v' => (string) substr($r['ctime'],11,5));
$temp[] = array('v' => (int) $r['totalKbpsin']);
$temp[] = array('v' => (int) $r['totalKbpsout']);
$rows[] = array('c' => $temp);
}
$table['rows'] = $rows;
$jsonTable = json_encode($table);
echo $jsonTable;
?>
And when I browse this page I get something like JSON Data:
{"cols":[{"label":"Tarih","type":"string"},{"label":"Inbound","type":"number"},{"label":"Outbound","type":"number"}],"rows":[{"c":[{"v":"14:00"},{"v":6213},{"v":891}]},{"c":[{"v":"15:00"},{"v":6914},{"v":915}]},{"c":[{"v":"16:00"},{"v":5645},{"v":1789}]},{"c":[{"v":"17:00"},{"v":5821},{"v":1771}]},{"c":[{"v":"18:00"},{"v":3242},{"v":1753}]},{"c":[{"v":"19:00"},{"v":7536},{"v":685}]},{"c":[{"v":"20:00"},{"v":6902},{"v":696}]},{"c":[{"v":"21:00"},{"v":7140},{"v":1184}]},{"c":[{"v":"22:00"},{"v":5971},{"v":502}]},{"c":[{"v":"23:00"},{"v":9506},{"v":1353}]},{"c":[{"v":"00:00"},{"v":8783},{"v":2855}]},{"c":[{"v":"01:00"},{"v":3125},{"v":1044}]},{"c":[{"v":"02:00"},{"v":2500},{"v":1858}]},{"c":[{"v":"03:00"},{"v":534},{"v":1721}]},{"c":[{"v":"04:00"},{"v":658},{"v":1940}]},{"c":[{"v":"05:00"},{"v":839},{"v":93}]},{"c":[{"v":"06:00"},{"v":1041},{"v":200}]},{"c":[{"v":"07:00"},{"v":1154},{"v":97}]},{"c":[{"v":"08:00"},{"v":2684},{"v":1467}]},{"c":[{"v":"09:00"},{"v":7297},{"v":2099}]},{"c":[{"v":"10:00"},{"v":4143},{"v":1244}]},{"c":[{"v":"11:00"},{"v":7645},{"v":1535}]},{"c":[{"v":"12:00"},{"v":4411},{"v":868}]},{"c":[{"v":"13:00"},{"v":5323},{"v":1119}]}]}
Graph is refreshed as image but not shows new values.
I check from HTTPFOX that get_new_data.php pull correct datas, Chart refreshes. But chart not change. Still same graph.
I think I solve it:
google.charts.load('visualization','current', {'packages':['corechart','bar'], 'language': 'en'});
google.setOnLoadCallback(drawBigChart);
function drawBigChart() {
var jsonData = $.ajax({
url: "get_new_data.php",
dataType: "json",
async: false
}).responseText;
var data = new google.visualization.DataTable(jsonData);
var options = {something for visualisation}
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
AND
$(document).ready(function(){
$("#dash_kullanicisayisi").load('kullanicisayisi.php')
$.ajax({
'url': 'get_new_data.php', // url should return only JSON data
'dataType': 'json',
'async': true
}).success(function(result) {
//Draw the chart again with the updated data
drawBigChart(result);
});
},60000);
});
solves my problem. Now chart refresh and populate new datas.
Thank for your assistances.
I'm trying to implement a FLOT chart from database, but I'm having a few problems...
I have a database with 2 rows: Data, Pcr
My files .php:
Datas.php
$dates=array();
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$date=$row['Date'];
$pcrs=(float)$row['Pcr'];
$dates[] = array(strtotime($date)*1000,$pcrs);
}
echo json_encode($dates);
I get the array:
[[1434240000000,7.2],[1434758400000,4.83],[1443052800000,4.85],[1445817600000,4.56],[1446163200000,4.5]]
I would like to get a chart from this array, but I don't know how to do that...
I have this file, and I know that it is incomplete...
Flot.php
<script>
$(document).ready(function(){
$.ajax({
type:’post’,
dataType:'json',
url:'datas.php',
success:function(data){
var datasets = {
"pcr": {
label: "Pcr",
data: dates
}
};
Could someone help me to do this chart?
Thank you very much
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.
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"]]
I am using Highcharts to display a chart containing dates/time and temperature of a room.
The javascript used to generate the chart is in the temperature.php file which user will be able to view, and the javascript will get data from a dataSorter.php file which contains SQL query to retrieve the results from MySQL for the chart to display.
Javascript to generate the chart in temperature.php:
<script type="text/javascript">
$(document).ready(function() {
var options = {
chart: {
renderTo: 'container',
type: 'line',
marginRight: 130,
marginBottom: 50
},
title: {
text: 'Temperature vs. Time',
x: -20 //center
},
subtitle: {
text: '',
x: -20
},
xAxis: {
categories: []
},
yAxis: {
title: {
text: 'Degrees Celcius'
},
plotLines: [{
value: 0,
width: 1,
color: '#808080'
}]
},
tooltip: {
formatter: function() {
return '<b>'+ this.series.name +'</b><br/>'+
this.x +': '+ this.y;
}
},
legend: {
layout: 'vertical',
align: 'right',
verticalAlign: 'top',
x: -10,
y: 100,
borderWidth: 0
},
series: []
}
$.getJSON("dataSorter.php", function(json) {
options.xAxis.categories = json[0]['data'];
options.series[0] = json[1];
chart = new Highcharts.Chart(options);
});
});
</script>
At this point, I have generated 4 drop down lists in temperature.php containing From Date, To Date, From Time and To Time. This will allow users to select a range which they wish to see the chart generate. (E.g 2014-01-20 00:00:00 to 2014-01-21 22:00:00). A button onclick will activate the function:
if(isset($_POST['sort'])){
$from=$_POST['SDate'];
$to=$_POST['EDate'];
$sTime=$_POST['STime'];
$eTime=$_POST['ETime'];
$start=$from." ".$sTime;
$end=$to." ".$eTime;
header('Location: dataSorter.php?start='.$start.'&end='.$end.'');
}
?>
$from = start date
$to = end date
$sTime = start time
$eTime = end time
$start = combine $from and $sTime to get a start date/time
$end = combine $to and $eTime to get a end date/time
dataSorter.php has the following codes:
<?php
$con = mysql_connect("localhost","root","password");
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("scsense", $con);
if(isset($_GET['start'])){
$start = $_GET['start'];
$end = $_GET['end'];
$sth = mysql_query("SELECT * FROM scsenseinfo WHERE roomID='501' AND (dateTime BETWEEN '$start' AND '$end') ORDER BY recordID");
$rows = array();
$rows['name'] = 'DateTime';
while($rr = mysql_fetch_assoc($sth)) {
$rows['data'][] = $rr['dateTime'];
}
$sth = mysql_query("SELECT * FROM scsenseinfo WHERE roomID='501' AND (dateTime BETWEEN '$start' AND '$end') ORDER BY recordID");
$rows1 = array();
$rows1['name'] = 'RoomTemperature';
while($r = mysql_fetch_array($sth)) {
$rows1['data'][] = $r['roomTemp'];
}
$result = array();
array_push($result,$rows);
array_push($result,$rows1);
$help = print json_encode($result, JSON_NUMERIC_CHECK);
mysql_close($con);
}
else{
$sth = mysql_query("SELECT * FROM (SELECT * FROM scsenseinfo WHERE roomID='501' ORDER BY recordID DESC LIMIT 5) AS tbl ORDER BY tbl.recordID ASC");
$rows = array();
$rows['name'] = 'DateTime';
while($rr = mysql_fetch_assoc($sth)) {
$rows['data'][] = $rr['dateTime'];
}
$sth = mysql_query("SELECT * FROM (SELECT * FROM scsenseinfo WHERE roomID='501' ORDER BY recordID DESC LIMIT 5) AS tbl ORDER BY tbl.recordID ASC");
$rows1 = array();
$rows1['name'] = 'RoomTemperature';
while($r = mysql_fetch_array($sth)) {
$rows1['data'][] = $r['roomTemp'];
}
$result = array();
array_push($result,$rows);
array_push($result,$rows1);
$help = print json_encode($result, JSON_NUMERIC_CHECK);
mysql_close($con);
}
//header('Location: L501TempSorter.php');
?>
If I have header('Location: L501TempSorter.php'); un-commented, the chart does not display a thing, even when onload of the page, without clicking the button to sort the dates. If it is commented, the chart is displayed onload, but clicking the button to sort the dates lead to dataSorter.php and stays on the page, which just displays the arrays containing the sorted dates. I really need help with this, thank you in advance!
You cannot use header when you have already printed something, like you sdo with //header('Location: L501TempSorter.php');.
If you are trying to save the output from print to the variable $help than you need to use sprint instead. Print will always output to the output buffer and always returns 1. This is true for any print function not starting with a s or vs the s before the print in the function name always indicates that it will return the resulting string instead of outputting it.
To solve your problem with the data not being displayed please post the onlcick code of the button. It should be an ajax call like
<script>
$.getJSON('dataSorter.php', {
sort: 'sortValue',
STime: /* get start value */,
ETime: /* get end value */,
SDate: /* get start value */,
EDate: /* get end value */
}, function(data) {
options.xAxis.categories = json[0]['data'];
options.series[0] = json[1];
chart = new Highcharts.Chart(options);
/* or anything that updates your chart */
});
</script>
In the php script run when the onClick function is executed. You should probably url encode your Location: in part
<?php
header('Location: dataSorter.php?start='.urlencode($start).'&end='.urlencode($end));
Though I don't understand why you are using header('Location: ...'); here anyways? You are already on the Server why tell the client browser to load a different location just include your script that is supposed to run now.
What is your purpose of using location, in case when you use this script only for return json? When you load json in javascirpt, you run your entire php script, so instead od returning json you are redirect to other location, as a result json is not loaded in javascript.