Display last few graphs using php - javascript

I want to get last 3 graph using refresh where the page automatically refresh in every 10 seconds. Here in this code when the page is refreshing automatically it start showing from beginning but i don't want that way.When the page will refresh every time it must show its last 3 graph. As here only 4 data available, it must show only D2 to D4 graph only even after refresh. When new data will be available it will display D3 to D5(which is not available right now) graph. How can i get last three graph after refreshing the page automatically?
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<meta http-equiv="Refresh" Content="10">
<title>Graph</title>
<style>
div.placeholder{
width: 500px;
height:250px
}
</style>
<?php
include("mydb.php");
// run query
$sql1 = "select * from tab where to_char(D,'dd/mm')='25-7'";
$stid1=oci_parse($conn, $sql1);
// set array
$arr1 = array();
if(!$stid1){
$e=oci_error($conn);
trigger_error(htmlentities($e[message],ENT_QUOTES),E_USER_ERROR);
}
$r1=oci_execute($stid1);
if(!$r1){
$e=oci_error($stid1);
trigger_error(htmlentities($e[message],ENT_QUOTES),E_USER_ERROR);
}
// look through query
while($row = oci_fetch_array($stid1,OCI_ASSOC)){
// add each row returned into an array
$arr1[] = array((strtotime($row['D'])*1000) , (float)$row['D1']);
}
?>
<?php
include("mydb.php");
// run query
$sql2 = "select * from tab where to_char(D,'dd/mm')='26-7'";
$stid2=oci_parse($conn, $sql2);
// set array
$arr2 = array();
if(!$stid1){
$e=oci_error($conn);
trigger_error(htmlentities($e[message],ENT_QUOTES),E_USER_ERROR);
}
$r2=oci_execute($stid2);
if(!$r2){
$e=oci_error($stid2);
trigger_error(htmlentities($e[message],ENT_QUOTES),E_USER_ERROR);
}
// look through query
while($row = oci_fetch_array($stid2,OCI_ASSOC)){
// add each row returned into an array
$arr2[] = array((strtotime($row['D'])*1000) , (float)$row['D1']);
}
?>
<?php
include("mydb.php");
// run query
$sql3 = "select * from tab where to_char(D,'dd/mm')='27-8'";
$stid3=oci_parse($conn, $sql3);
// set array
$arr3 = array();
if(!$stid3){
$e=oci_error($conn);
trigger_error(htmlentities($e[message],ENT_QUOTES),E_USER_ERROR);
}
$r3=oci_execute($stid3);
if(!$r3){
$e=oci_error($stid3);
trigger_error(htmlentities($e[message],ENT_QUOTES),E_USER_ERROR);
}
// look through query
while($row = oci_fetch_array($stid3,OCI_ASSOC)){
// add each row returned into an array
$arr3[] = array((strtotime($row['D'])*1000) , (float)$row['D1']);
}
?>
<?php
include("mydb.php");
// run query
$sql4 = "select * from dat where to_char(D,'dd/mm')='28-9'";
$stid4=oci_parse($conn, $sql4);
// set array
$arr4 = array();
if(!$stid4){
$e=oci_error($conn);
trigger_error(htmlentities($e[message],ENT_QUOTES),E_USER_ERROR);
}
$r4=oci_execute($stid4);
if(!$r4){
$e=oci_error($stid4);
trigger_error(htmlentities($e[message],ENT_QUOTES),E_USER_ERROR);
}
// look through query
while($row = oci_fetch_array($stid4,OCI_ASSOC)){
// add each row returned into an array
$arr4[] = array((strtotime($row['D'])*1000) , (float)$row['D1']);
}
?>
<script type="text/javascript" src="jquery-1.11.3.min.js"></script>
<script type="text/javascript" src="jquery.flot.js"></script>
<script type="text/javascript" src="excanvas.js"></script>
<script type="text/javascript" src="jquery.flot.symbol.min.js"></script>
<script type="text/javascript" src="jquery.flot.axislabels.js"></script>
<script type="text/javascript" src="jquery.flot.time.min.js"></script>
<script type="text/javascript">
var interval=2000;
function getdata(){
var data1=<?php echo json_encode($arr1); ?>;
var data2=<?php echo json_encode($arr2); ?>;
var data3=<?php echo json_encode($arr3); ?>;
var data4=<?php echo json_encode($arr4); ?>;
return [data1,data2,data3,data4];
}
var options={
    
series: {
         lines: {
             show: true,
             lineWidth: 2,
             fill: true
         },
points:{
show: "triangle"
}
     },
xaxis: {
                 
axisLabel: "Time",
         axisLabelUseCanvas: true,
         axisLabelFontSizePixels: 12,
         axisLabelFontFamily: 'Verdana, Arial',
         axisLabelPadding: 10
     },
     yaxis: {
        
         axisLabel: "Data loading",
         axisLabelUseCanvas: true,
          axisLabelFontSizePixels: 12,
         axisLabelFontFamily: 'Verdana, Arial',
         axisLabelPadding: 6
     },
legend: {       
         labelBoxBorderColor: "#B0D5FF"
     },
grid: {
hoverable: true,
clickable: true,
backgroundColor: {
colors: ["#B0D5FF", "#5CA8FF"]
}
             }
};
$(document).ready(function () {
var dataset=[
{
label: "D1",
data: getdata()[0],
points: {
symbol: "triangle"
}
},
{
label: "D2",
data: getdata()[1],
points: {
symbol: "circle"
}
},
{
label: "D3",
data: getdata()[2],
points: {
symbol: "triangle"
}
},
{
label: "D4",
data: getdata()[3],
points: {
symbol: "triangle"
}
}
];
var counter=0;
for(var i=1,j=0;i<dataset.length,j<$('div.placeholder').length;i++,j++){
$.plot("div.placeholder:eq(" + j + ")", [dataset[j]], options);
counter=i;
}
function update() {
       
$('div.placeholder:visible:first').hide();
$('div.placeholder:last').after($('<div>').addClass('placeholder'));
$.plot("div.placeholder:last", [dataset[counter++]], options);
 
if(dataset.length > counter) {
setTimeout(update, interval);
}
}
 
    setTimeout(update, interval);
});
</script>
</head>
<body>
<center>
<h3><b><u>Chart</u></b></h3>
<div class="placeholder"></div>
<div class="placeholder"></div>
<div class="placeholder"></div>
</center>
</body>
</html>

Related

Highcharts loaded via ajax, issue to dynamically create yAxis

I have a page that dynamically updates a HighCharts graph from a multiselect dropdown.
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script src="https://code.highcharts.com/highcharts.js"></script>
<script src="https://code.highcharts.com/modules/series-label.js"></script>
<script src="https://code.highcharts.com/modules/exporting.js"></script>
<script src="https://code.highcharts.com/modules/export-data.js"></script>
</head>
<body>
<!-- FIELDS -->
<div id="fields">
<form method="post" action="">
<select id="f" name="f[]" multiple>
<option value="rss1" select>1RSS(dB)</option>
<option value="rss2">2RSS(dB)</option>
<option value="rqly">RQly(%)</option>
<option value="rsnr">RSNR(dB)</option>
</select>
</form>
</div>
<!-- GRAPH -->
<div id="graph">No selection</div>
<script>
var updateChart = function(json) {
// console.log(json)
var options = {
chart: {
renderTo: 'graph',
type: 'line',
zoomType: 'x'
},
title: { text: null },
plotOptions: {
series: {
label: {
connectorAllowed: false
},
pointStart: 0
}
},
series: []
}
options.series = json;
var chart = new Highcharts.Chart(options);
// update yaxis
for (i=0; i<json.length; i++) {
if(i==0) {
// it seems that a yAxis already exist when graph is initialized. Did not find a smarter way to destroy it...
chart.yAxis[0].update({ title: { text: json[i].name }});
} else {
chart.addAxis({ title: { text: json[i].name } });
}
}
}
$(document).ready(function() {
$('#f').change(function() {
var requestParams = { f: $('#f').val() };
$.post('analysisajax.php', requestParams, updateChart);
});
});
</script>
</body>
</html>
Now, my analysisajax.php file looks like this:
<?php
header("Content-type: text/json");
// Initialize the session
session_start();
// Include config file
require_once "config.php";
$jsonObject = array();
$yaxis = 0;
foreach($_POST["f"] as $v) {
$data = array();
$sql = "SELECT $v FROM log WHERE id_user = " . $_SESSION["id_user"];
$result = $link->query($sql);
while($row = $result->fetch_row()) {
$data[] = $row[0];
}
$jsonObject[] = array(
"name" => $v,
"data" => $data,
"yAxis"=>$yaxis
);
$yaxis++;
}
$myJSON = json_encode($jsonObject, JSON_NUMERIC_CHECK);
echo $myJSON;
// Close connection
mysqli_close($link);
?>
When I'm selecting 1 value from the form, the graph loads without problem, but as soon as more than 1 value is selected from the dropdown, the graph fails with the following trace:
highcharts.src.js:498 Uncaught Error: Highcharts error #18: www.highcharts.com/errors/18
at Object.a.error (highcharts.src.js:498)
at highcharts.src.js:32669
at Array.forEach (<anonymous>)
at r.<anonymous> (highcharts.src.js:32621)
at a.fireEvent (highcharts.src.js:2635)
at r.bindAxes (highcharts.src.js:32618)
at r.init (highcharts.src.js:32482)
at a.Chart.initSeries (highcharts.src.js:26913)
at highcharts.src.js:28765
at Array.forEach (<anonymous>)
I feel that the issue is coming from my dynamic construction of yAxis but can't find a way to make it work. Any idea? Thanks a lot.
I eventually made it work with the following solution:
In the analysisajax.php script, I no longer generate the yaxis. I only send name and data.
The code to generate the graph now looks like this:
var updateChart = function(json) {
//console.log(json)
var options = {
chart: {
renderTo: 'graph',
type: 'line',
zoomType: 'x'
},
title: { text: null },
yAxis:[],
legend: {
layout: 'vertical',
align: 'right',
verticalAlign: 'bottom'
},
plotOptions: {
series: {
label: {
connectorAllowed: false
},
pointStart: 0
}
},
series: [],
tooltip: { shared: true }
}
var chart = new Highcharts.Chart(options);
// update axis and series
for (i=0; i<json.length; i++) {
// add axis
chart.addAxis({ title: { text: json[i].name } });
// add serie
var a = chart.series.length;
var seriesOptions = {
name: json[i].name,
data: json[i].data,
yAxis: a
}
chart.addSeries(seriesOptions,true);
chart.options.series.push(seriesOptions);
}
}
$(document).ready(function() {
$('#f').change(function() {
var requestParams = { f: $('#f').val() };
$.post('analysisajax.php', requestParams, updateChart);
//return false;
});
});

Wrong date in highstock Chart

How can I incorporate the correct date into my high stock chart? I keep getting the months January to February (correct range should be from July to August) in my slider, which is incorrect. In my PHP I convert the date/time from my database into a JavaScript timestamp, but still doesn't work. Any help would be great, thanks!
Output Array: data.txt
Current high stocks Chart:
PHP & JS and HTML:
<?php
$stmt = mysqli_prepare($con, "SELECT date, IFNULL(AT,'null') FROM test");
$result = array('date' => array(), 'AT' => array());
if ($stmt) {
mysqli_stmt_execute($stmt);
mysqli_stmt_bind_result($stmt, $date, $at);
while (mysqli_stmt_fetch($stmt)) {
$result['date'][] = $date;
$result['AT'][] = (int)$at;
$stamp = strtotime($date); // get unix timestamp
$time = $stamp*1000;
}
mysqli_stmt_close($stmt);
}
?>
<!DOCTYPE html>
<html >
<!--<![endif]-->
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="https://code.highcharts.com/stock/highstock.js"></script>
<script src="https://code.highcharts.com/highcharts-more.js"></script>
<script src="https://code.highcharts.com/modules/data.js"></script>
<script>
$(function(data) {
$('#chart2').highcharts('StockChart', { //Stock chart - might need zones to match gauges
rangeSelector : {
buttons : [{
type : 'hour',
count : 3,
text : '3h'
}, {
type : 'day',
count : 2,
text : '2D'
}, {
type : 'week',
count : 1,
text : '1W'
}, {
type : 'month',
count : 1,
text : '1M'
}, {
type : 'all',
count : 1,
text : 'All'
}],
selected : 2,
},
title: {
text: 'Power'
},
yAxis: [{
title: {
text: 'Bat V'
},
height: 400,
lineWidth: 2,
oposite: true
}, {
title: { // yAxis 1 ie secondary y-axis
text: 'Solar V'
},
//top: 200,
height: 400,
offset: 25,
lineWidth: 2,
oposite: false
}],
xAxis:{
type: <?php echo json_encode($time) ?>,
},
series: [{
pointInterval: 24 * 3600 * 1000,
type: 'line',
data: <?php echo json_encode($result['AT']) ?>
},],
}); //end of stockchart graphic
// end of get function
}); // end of graphing function
</script>
</head>
<body>
<?php echo $time; ?>
<br><br /><br /><br />
<div id="chart2" style="width:100%; height:600px;"></div>
</body>
</html>
Based on your Output Array: data.txt which is [["2017-07-25 16:44",12],["2017-07-25 17:00",12],...] it should be [[1500981240000,12],[1500982200000,12],...] so fix is $result['date'][] = strtotime($date)*1000 get unix timestamp in milliseconds
<?php
$stmt = mysqli_prepare($con, "SELECT date, IFNULL(AT,'null') FROM test");
$result = array('date' => array(), 'AT' => array());
if ($stmt) {
mysqli_stmt_execute($stmt);
mysqli_stmt_bind_result($stmt, $date, $at);
while (mysqli_stmt_fetch($stmt)) {
$result['date'][] = strtotime($date)*1000; // get unix timestamp in milliseconds
$result['AT'][] = (int)$at;
$stamp = strtotime($date); // get unix timestamp
$time = $stamp*1000;
}
mysqli_stmt_close($stmt);
}
?>

Dynamic updates with highcharts

I'm working with Highcharts and Highstock from a few weeks ago. Step by step, following the documentation and help online, I have builded some charts with interesting options. But now I have a question, and my skills with mysql and php are limited.
I get temperature values from a data base, every minute. I use a php file to connect to database, and then I build the chart. Now, I want to update the chart like in this example. But I can't find a right way. I was reading in Highcharts documentation, and Stackoverflow some answers, but I can't implement into my code.
I was working in 2 ways to implement the dynamic updates. The first one is:
<?php
function conectarBD(){
$server = "localhost";
$usuario = "user";
$pass = "password";
$BD = "databasename";
$conexion = mysqli_connect($server, $usuario, $pass, $BD);
if(!$conexion){
echo 'Ha sucedido un error inexperado en la conexion de la base de datos<br>';
}
return $conexion;
}
function desconectarBD($conexion){
$close = mysqli_close($conexion);
if(!$close){
echo 'Ha sucedido un error inexperado en la desconexion de la base de datos<br>';
}
return $close;
}
function getArraySQL($sql){
$conexion = conectarBD();
if(!$result = mysqli_query($conexion, $sql)) die();
$rawdata = array();
$i=0;
while($row = mysqli_fetch_array($result))
{
$rawdata[$i] = $row;
$i++;
}
desconectarBD($conexion);
return $rawdata;
}
$sql = "SELECT Probe1,Time from table2;";
$rawdata = getArraySQL($sql);
for($i=0;$i<count($rawdata);$i++){
$time = $rawdata[$i]["Time"];
$date = new DateTime($time);
$rawdata[$i]["Time"]=$date->getTimestamp()*1000;
}
?>
<HTML>
<BODY>
<meta charset="utf-8">
<script src="https://code.jquery.com/jquery.js"></script>
<script src="http://code.highcharts.com/stock/highstock.js"></script>
<script src="http://code.highcharts.com/modules/exporting.js"></script>
<div id="container">
</div>
<script type='text/javascript'>
$(function () {
$(document).ready(function() {
Highcharts.setOptions({
global: {
useUTC: false
}
});
var chart;
$('#container').highcharts({
chart: {
type: 'spline',
animation: Highcharts.svg, // don't animate in old IE
marginRight: 10,
events: {
load: function () {
var series = this.series[0];
setInterval(function () {
<?php
for($i = 0 ;$i<count($rawdata);$i++){
?>
series.addPoint([<?php echo $rawdata[$i]["Time"];?>,<?php echo $rawdata[$i]["Probe1"];?>], true, true);
<?php } ?>
}, 90000);
}
}
},
title: {
text: 'Tunnel temperature'
},
xAxis: {
type: 'datetime',
tickPixelInterval: 150
},
yAxis: {
title: {
text: 'ºC'
},
plotLines: [{
value: 0,
width: 1,
color: '#808080'
}]
},
tooltip: {
formatter: function() {
return '<b>'+ this.series.name +'</b><br/>'+
Highcharts.dateFormat('%d-%b %H:%M', this.x) +'<br/>'+
'<b>'+ Highcharts.numberFormat(this.y, 1) +'</b>';
}
},
legend: {
enabled: true
},
exporting: {
enabled: true
},
series: [{
name: 'Probe-1',
data: (function() {
var data = [];
<?php
for($i = 0 ;$i<count($rawdata);$i++){
?>
data.push([<?php echo $rawdata[$i]["Time"];?>,<?php echo $rawdata[$i]["Probe1"];?>]);
<?php } ?>
return data;
})()
}]
});
});
});
</script>
</html>
And this other way:
Connection to datatest2.php:
<?php
//convert the date values to Unix Timestamp
//Convert from 2017-02-28 19:30:01 to Tuesday, February 28 2017 19:30:01
$con = mysql_connect("localhost","username","password");
if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db("databasename", $con);
$result = mysql_query("SELECT * FROM table2");
while ($row = mysql_fetch_array($result)) {
$uts=strtotime($row['Time']); //convertir a Unix Timestamp
$date=date("l, F j Y H:i:s",$uts);
//echo $valor3 . “\t” . $row[$valor2]. “\n”;
echo $date . "\t" . $row['Probe1'] . "\n";
}
mysql_close($con); ?>
And the php file for the chart:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>Highstock & multiple</title>
<script src="https://code.jquery.com/jquery.js"></script>
<script src="http://code.highcharts.com/stock/highstock.js"></script>
<script src="http://code.highcharts.com/modules/exporting.js"></script>
<script type="text/javascript">
var chart;
$(document).ready(function() {
var options = {
chart: {
renderTo: 'container',
defaultSeriesType: 'line',
marginRight: 130,
marginBottom: 25
},
title: {
text: 'Temperature Tunnel',
x: -20 //center
},
subtitle: {
text: '',
x: -20
},
rangeSelector: {
buttons: [
{
type: 'all',
text: 'all'
}, {
type: 'week',
count: 1,
text: '1w'
}, {
type: 'day',
count: 1,
text: '1d'
}, {
type: 'hour',
count: 18,
text: '18h'
}, {
type: 'hour',
count: 12,
text: '12h'
}, {
type: 'hour',
count: 6,
text: '6h'
}]
},
xAxis: {
type: 'datetime',
tickWidth: 0,
gridLineWidth: 1,
labels: {
align: 'center',
x: -3,
y: 20,
formatter: function() {
return Highcharts.dateFormat('%d-%b %H:%M', this.value);
}
}
},
yAxis: {
title: {
text: 'Celsius degrees'
},
plotLines: [{
value: 0,
width: 1,
color: '#808080'
}]
},
tooltip: {
formatter: function() {
return Highcharts.dateFormat('%d-%b %H:%M', this.x) +': <b>'+ this.y + '</b>';
}
},
legend: {
layout: 'vertical',
align: 'right',
verticalAlign: 'top',
x: -10,
y: 100,
borderWidth: 0
},
series: [{
name: 'Probe1'
}]
}
jQuery.get('datatest2.php', null, function(tsv) {
var lines = [];
traffic = [];
try {
// split the data return into lines and parse them
tsv = tsv.split(/\n/g);
jQuery.each(tsv, function(i, line) {
line = line.split(/\t/);
date = Date.parse(line[0] +' UTC');
traffic.push([
date,
parseInt(line[1].replace(',', ''), 10)
]);
});
} catch (e) { }
options.series[0].data = traffic;
chart = Highcharts.stockChart (options);
setInterval(function() { tsv; }, 30000);
pollChart.series[0].setData(data);
});
});
</script>
</head>
<body>
<div id="container" style="width: 100%; height: 400px; margin: 0 auto"></div>
</body>
</html>
Can you help me to find and fix the mistake?
Thanks!
Alex.
Using a combination of your first example and the JSFiddle that you posted, I would try something like this:
chart: {
events: {
load: function () {
var series = this.series[0];
setInterval(function () {
<?php
for($i = 0 ;$i<count($rawdata);$i++){
?>
series.addPoint([<?php echo $rawdata[$i]["Time"];?>,<?php echo $rawdata[$i]["Probe1"];?>], true, true);
<?php } ?>
}, 1000);
}
}
}
Note that I have no idea whether your PHP code there is actually retrieving the data that you wanted, I have simply copied it from your example and made the assumption that that part of the code was ok.
The key here is the chart.events.load property, this takes a function that fires once the chart has finished loading. By calling setInterval here, your function will fire continuously after the chart finishes loading the first time.
By calling series.addPoint, your chart will redraw every time a new point is added, which I believe is what you want.
More information is available here about the load property.

Highstock don't draw

http://www.highcharts.com/stock/demo/basic-line
It's my code for json.php
<?php
header("content-type: application/json");
define('HOST', 'localhost');
define('USER', 'root');
define('PASSWORD', 'password');
define('NAME_BD', 'bd');
$connect = mysql_connect(HOST, USER, PASSWORD)
or die("die"
.mysql_error( ));
mysql_select_db(NAME_BD, $connect)
or die ("wtf"
.mysql_error( ));
$result = mysql_query("SELECT UNIX_TIMESTAMP(`Time`) * 1000 as datetime, `Current A` as A FROM `Table`")
or die ("die".mysql_error( ));
while ($row = mysql_fetch_array($result)) {
$data[] = $row['datetime'];
$datab[] = $row['A'];
}
echo '?(' . "\n" . '['. "\n";
$count = count($data);
for ($i=0; $i<$count; $i++)
{
echo '['. str_replace('"', "", json_encode($data[$i], JSON_HEX_APOS)) . ',' . str_replace('"', "", json_encode($datab[$i], JSON_HEX_APOS)) .']' . ',' . "\n";
}
echo ']);';
?>
I refresh my page and highstock don't draw. Please help me.
It's my stock.html
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Highstock Example</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<style type="text/css">
${demo.css}
</style>
<script type="text/javascript">
$(function () {
$.getJSON('http://192.168.1.175/json.php', function (data) {
// Create the chart
$('#container').highcharts('StockChart', {
rangeSelector : {
selected : 1
},
title : {
text : 'AAPL Stock Price'
},
series : [{
name : 'AAPL',
data : data
}]
});
});
});
</script>
</head>
<body>
<script src="https://code.highcharts.com/stock/highstock.js"></script>
<script src="https://code.highcharts.com/stock/modules/exporting.js"></script>
<div id="container" style="height: 400px; min-width: 310px"></div>
</body>
</html>
Stock.html call json.php but when a refresh stock.html i don't see draw.
Please help me
Please try below code
in Ajax code
function drawGrap()
{
$.ajax({
type: "POST",
url: 'graph.php',
data: '',
success: function(json) {
drawSalesChart(json);
}
});
}
in graph.php
<?php
if(!empty($data))
{
foreach ($data as $d)
{
$time = strtotime($d['date']);
$date = date("Y-m-d",$time);
$graphData[$date][0] = 'Date.UTC('. date("Y",$time) .','. (date("m",$time)-1) .','. date("d",$time) .')';
$graphData[$date][1] = $d['count'];
}
}
sort($graphData);
//Convert result array to json format
$jsonGraphData = json_encode($graphData);
$jsonGraphData = str_replace('"', '', $jsonGraphData);
echo $jsonGraphData;
?>
After response
function drawSalesChart( data)
{
$('#GraphID').css("height", "400px");
$('#GraphID').highcharts('StockChart', {
title: {
text: 'Daily Sales'
},
colors: ['#920000'],
navigator: {
enabled: false
},
rangeSelector: {
selected: 5,
buttons: [
{
type: 'week',
count: 1,
text: '1 Week'
},
{
type: 'month',
count: 1,
text: '1 Month'
},
{
type: 'month',
count: 3,
text: '3 Months'
},
{
type: 'month',
count: 6,
text: '6 Months'
},
{
type: 'year',
count: 1,
text: '1 Year'
},
{
type: 'all',
text: 'All'
}
],
buttonTheme: {
width: 100,
padding: 5,
style: {
color: '#000000'
}
}
},
series: [{
name: 'Kr',
type: 'area',
data: eval(data),
tooltip: {
valueDecimals: 2
},
fillColor: {
linearGradient: {
x1: 0,
y1: 0,
x2: 0,
y2: 1
},
stops: [
[0, '#FF4848'],
[1, '#ffe1e1'],
]
}
}]
});
}

Draw a real-time flot chart by fetching data from database and store it into an array using JavaScript

I'm trying to draw a real-time update flot chart by retrieving data from oracle database and store it into an array
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>Untitled Document</title>
<script type="text/javascript" src="jquery-1.11.3.min.js"></script>
<script type="text/javascript" src="js plugins/excanvas.js"></script>
<script type="text/javascript" src="js plugins/jquery.flot.js"></script>
<script type="text/javascript" src="js plugins/jquery.flot.time.min.js"></script>
<script type="text/javascript" src="js plugins/jquery.flot.axislabels.js"></script>
<script type="text/javascript">
var data=[];
var dataset;
var updateInterval = 1000;
function getdata(){
var con= new ActiveXObject('ADODB.Connection');
var connectionString="Provider= OraOLEDB.Oracle;User id=SYSTEM;Password=sandp;datasource=ORA";
con.Open(connectionString);
var rs=new ActiveXObject('ADODB.Recordset');
rs.Open("select W_DATE,DATA from cet", con);
var i=0;
while(!rs.eof)
{
data.push([rs(0)*1000,rs(1)]);
data[i++];
rs.movenext;
}
rs.close;
con.close;
}
var options= {
     series: {
         lines: {
             show: true,
             lineWidth: 1.2,
             fill: true
         }
     },
     xaxis: {
         mode: "time",
         tickSize: [2, "second"],
         timeformat:"%m/%d %H:%M", ,
         axisLabel: "Time",
         axisLabelUseCanvas: true,
         axisLabelFontSizePixels: 12,
         axisLabelFontFamily: 'Verdana, Arial',
         axisLabelPadding: 10
     },
     yaxis: {
         min: 0,
         max: 100,       
         tickSize: 5,
         tickFormatter: function (v, axis) {
             if (v % 10 == 0) {
                 return v;
             }
else {
                 return "";
             }
         },
         axisLabel: "Data loading",
         axisLabelUseCanvas: true,
          axisLabelFontSizePixels: 12,
         axisLabelFontFamily: 'Verdana, Arial',
         axisLabelPadding: 6
     },
     legend: {       
         labelBoxBorderColor: "#fff"
     },
grid: {
backgroundColor: {
colors: ["#B0D5FF", "#5CA8FF"]
}
        }
};
$(document).ready(function () {
     getdata();
 
    dataset = [
        { label: "Data", data: data }
     ];
 
    $.plot($("#container"), dataset, options);
 
    function update() {
         data.shift();
getdata();
 
        $.plot($("#container"), dataset, options)
        setTimeout(update, updateInterval);
     }
 
    update();
});
</script>
</head>
<body>
<div id="container" style="width:1360px; height:1200px"></div>
</body>
</html>
the error i'm getting is that Object is no longer valid
My dates are 25th feb 2015 00:14, 25th feb 2015 00:33, 25th feb 2015 00:53 but showing as follows
I want the x-axis as follows-
how can i fix this and get x-axis as i wanted?
please help

Categories

Resources