Highcharts xaxis is off by several hours - javascript

I'm pulling values from a MySQL database using PHP, and attempting to plot them using Highcharts. The problem I'm finding is the xaxis values seems to be off by 4 hours. Searching through past threads, some people place the useUTC: false in the global chart options, but it did not seem to work for me.
global:{
useUTC: false
}
Here is the code I'm using to set up the chart. I'm a javascript newbie, so it's very possible I did something stupid in here. Any suggestions?
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Temperature Data from XBee</title>
<script src="js/jquery-1.11.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var options = {
chart: {
renderTo: 'container',
type: 'line',
marginRight: 130,
marginBottom: 25
},
title: {
text: 'Wireless Sensor Data: Temperature (F)',
x: -20 //center
},
global: {
useUTC: false
},
yAxis: {
title: {
text: 'temperature'
},
type: 'double',
min: 0,
},
xAxis: {
title: {
text: 'time'
},
type: 'datetime'
},
series: [{
name: 'Temperature',
data: []
}]
}
$.getJSON("data.php", function(json) {
options.series[0].data = json;
chart = new Highcharts.Chart(options);
});
});
</script>
<script src="js/highcharts.js"></script>
<script src="js/themes/grid-light.js"></script>
</head>
<body>
<div id="container" style="min-width: 800px; height: 800px; margin: 0 auto"></div>
</body>
</html>
Here is my PHP code that queries the database and puts the data into the JSON format.
<?php
$con = mysql_connect("localhost","root","raspberry");
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("xbee", $con);
$result = mysql_query("SELECT time, temperature FROM data WHERE time >= DATE_SUB(NOW(), INTERVAL 1 HOUR)");
$rows = array();
while($r = mysql_fetch_array($result)) {
extract($r);
$time = strtotime($r[0]);
$time *=1000;
$row[0] = $time;
$row[1] = $r[1];
array_push($rows,$row);
}
print json_encode($rows, JSON_NUMERIC_CHECK);
mysql_close($con);
?>
This is what my JSON format looks like.
[[1414172722000,73.4],[1414172727000,73.4],[1414172732000,73.4],[1414172737000,75.2],[1414172742000,75.2],[1414172747000,75.2],[1414172753000,73.4],[1414172758000,75.2],[1414172763000,73.4],[1414172768000,75.2],[1414172773000,75.2],[1414172778000,75.2],[1414172783000,75.2],[1414172788000,73.4],[1414172793000,73.4],[1414172798000,75.2],[1414172803000,75.2],[1414172809000,75.2],[1414172814000,75.2],[1414172819000,75.2],[1414172824000,73.4],[1414172829000,75.2],[1414172834000,75.2],[1414172839000,75.2],[1414172844000,75.2],[1414172849000,75.2],[1414172854000,75.2],[1414172860000,75.2],[1414172865000,75.2],[1414172870000,75.2],[1414172875000,75.2],[1414172880000,75.2],[1414172885000,75.2],[1414172890000,75.2],[1414172895000,75.2],[1414172900000,75.2],[1414172905000,73.4],[1414172910000,75.2],[1414172916000,75.2],[1414172921000,75.2],[1414172926000,75.2],[1414172931000,75.2],[1414172936000,75.2],[1414172941000,75.2],[1414172946000,75.2],[1414172951000,75.2],[1414172956000,75.2],[1414172961000,75.2],[1414172966000,73.4],[1414172972000,75.2],[1414172977000,75.2],[1414172982000,73.4],[1414172987000,75.2],[1414172992000,75.2],[1414172997000,73.4],[1414173002000,75.2],[1414173007000,75.2],[1414173012000,75.2],[1414173017000,75.2],[1414173022000,75.2],[1414173028000,75.2],[1414173033000,75.2],[1414173038000,75.2],[1414173043000,75.2],[1414173048000,75.2],[1414173053000,75.2],[1414173058000,75.2],[1414173063000,71.6],[1414173068000,75.2],[1414173073000,75.2],[1414173079000,75.2],[1414173084000,75.2],[1414173089000,75.2],[1414173094000,75.2],[1414173099000,75.2],[1414173104000,75.2],[1414173109000,75.2],[1414173114000,75.2],[1414173119000,75.2],[1414173124000,75.2],[1414173129000,75.2],[1414173135000,75.2],[1414173140000,75.2],[1414173145000,75.2],[1414173150000,75.2],[1414173155000,75.2],[1414173160000,75.2],[1414173165000,75.2],[1414173170000,75.2],[1414173175000,75.2],[1414173180000,75.2],[1414173185000,75.2],[1414173191000,75.2],[1414173196000,75.2],[1414173201000,75.2],[1414173206000,75.2],[1414173211000,75.2],[1414173216000,75.2],[1414173221000,75.2],[1414173226000,75.2],[1414173231000,75.2],[1414173236000,75.2],[1414173241000,75.2],[1414173247000,75.2],[1414173252000,75.2],[1414173257000,75.2],[1414173262000,75.2],[1414173267000,75.2],[1414173272000,75.2],[1414173277000,75.2],[1414173282000,75.2],[1414173287000,75.2],[1414173292000,75.2],[1414173298000,75.2],[1414173303000,75.2],[1414173308000,75.2],[1414173313000,75.2],[1414173318000,75.2],[1414173323000,75.2],[1414173328000,75.2],[1414173333000,75.2],[1414173338000,75.2],[1414173343000,75.2],[1414173348000,75.2],[1414173354000,75.2],[1414173359000,75.2],[1414173364000,75.2],[1414173369000,75.2],[1414173374000,75.2],[1414173379000,75.2],[1414173384000,75.2],[1414173389000,75.2],[1414173394000,75.2],[1414173399000,75.2],[1414173404000,75.2],[1414173410000,75.2],[1414173415000,75.2],[1414173420000,75.2],[1414173425000,75.2],[1414173430000,75.2],[1414173435000,75.2],[1414173440000,75.2],[1414173445000,75.2],[1414173450000,75.2],[1414173455000,73.4],[1414173461000,75.2],[1414173466000,75.2],[1414173471000,75.2],[1414173476000,75.2],[1414173481000,75.2],[1414173486000,75.2],[1414173491000,75.2],[1414173496000,75.2],[1414173501000,73.4],[1414173506000,75.2],[1414173511000,75.2],[1414173517000,73.4],[1414173522000,75.2],[1414173527000,75.2],[1414173532000,75.2],[1414173537000,75.2],[1414173542000,75.2],[1414173547000,75.2],[1414173552000,73.4],[1414173557000,75.2],[1414173562000,75.2],[1414173567000,75.2],[1414173573000,75.2],[1414173578000,75.2],[1414173583000,75.2],[1414173590000,32],[1414173651000,75.2],[1414173711000,75.2],[1414173771000,73.4],[1414173831000,75.2],[1414173891000,73.4],[1414173951000,75.2],[1414174011000,73.4],[1414174071000,75.2],[1414174131000,73.4],[1414174191000,75.2],[1414174251000,71.6],[1414174311000,73.4],[1414174372000,73.4],[1414174432000,73.4],[1414174492000,73.4],[1414174552000,73.4],[1414174612000,73.4],[1414174672000,73.4],[1414174732000,73.4],[1414174792000,73.4],[1414174852000,73.4],[1414174912000,73.4],[1414174972000,73.4],[1414175032000,73.4],[1414175093000,73.4],[1414175153000,73.4],[1414175213000,73.4],[1414175273000,73.4],[1414175333000,73.4],[1414175393000,73.4],[1414175453000,73.4],[1414175513000,73.4],[1414175573000,73.4],[1414175633000,73.4],[1414175693000,73.4],[1414175753000,73.4],[1414175814000,73.4],[1414175874000,73.4],[1414175934000,73.4],[1414175994000,73.4],[1414176054000,73.4],[1414176114000,73.4],[1414176174000,73.4],[1414176234000,75.2],[1414176294000,75.2]]

I found a solution, not sure if this is the most elegant, but it is producing the correct results now. It looks like when using the strtotime conversion in PHP, it was using the default GMT timezone. In the PHP script, I added the date_default_time_set('UTC') and it works. Hopefully this will help someone in the future.
<?php
$con = mysql_connect("localhost","root","raspberry");
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("xbee", $con);
$result = mysql_query("SELECT time, temperature FROM data WHERE time >= DATE_SUB(NOW(), INTERVAL 1 HOUR)");
$rows = array();
while($r = mysql_fetch_array($result)) {
date_default_timezone_set('UTC');
extract($r);
$time = strtotime($r[0]);
$time *=1000;
$row[0] = $time;
$row[1] = $r[1];
array_push($rows,$row);
}
print json_encode($rows, JSON_NUMERIC_CHECK);
mysql_close($con);
?>

Related

Live data from MySQL with highchart

I found this Highchart live data example Live data. I try to use my own data which is come from MySQL so, I change the $y in live-server-data.php to receive the data after use function fetch_assoc().
HTML Code
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Highcharts Example</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.10.1.js"></script>
<script type="text/javascript" src="http://code.highcharts.com/highcharts.js"></script>
</head>
<body>
<div id="container" style="width: 800px; height: 400px; margin: 0 auto"></div>
</body>
</html>
JS
var chart; // global
function requestData() {
$.ajax({
url: 'live-server-data.php',
success: function(point) {
var series = chart.series[0],
shift = series.data.length > 20; // shift if the series is longer than 20
chart.series[0].addPoint(eval(point), true, shift);
// call it again after one second
setTimeout(requestData, 1000);
},
cache: false
});
}
$(document).ready(function() {
chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
defaultSeriesType: 'spline',
events: {
load: requestData
}
},
title: {
text: 'Live random data'
},
xAxis: {
type: 'datetime',
tickPixelInterval: 150,
maxZoom: 20 * 1000
},
yAxis: {
minPadding: 0.2,
maxPadding: 0.2,
title: {
text: 'Value',
margin: 80
}
},
series: [{
name: 'Random data',
data: []
}]
});
});
PHP code
<?php
$conn = new mysqli($servername, $username, $password, $dbname);
if($conn->connect_error){
die("Connection failed: ".$conn->connect_error);
}
$sql_1 = "SELECT SensorData AS power FROM $tbname where SensorID = '1'";
$result_1=$conn->query($sql_1);
while($row = $result_1->fetch_assoc()){
$y = $row['power'];
}
$conn->close();
header("Content-type: text/json");
multiplied by 1000.
$x = time() * 1000;
$ret = array($x, $y);
echo json_encode($ret);
?>
The graph is moved but it not shows any data.
So I press F12 on Chrome Browser and I found this thing.
I think "14.600" may be the cause of my problem. Please tell me if you know the solution to solve this problem. Thank you so much.
I think the graph required an array that contains numeric values in it. In your case one value is numeric but another one is string so convert all the values to numeric i.e. either integer or float. (Float is preferred here) and pass that array to the graph.

live data chart not working

hi everyone im working on real-time java script chart to display data from a database but all i get is nothing its not catching data from data base
i used this php code
<?php
header("Content-type: text/json");
$servername = "localhost";
$username = "root";
$password = "";
$value = $_GET['value'];
$date = time() * 1000;
$ret = array($date, $value);
echo json_encode($ret);
$conn = mysql_connect($servername, $username, $password);
if ($conn) {
echo "Connected successfully";
}
else {
echo "connection failed";
}
$conndb = mysql_select_db('database', $conn);
echo "<br>";
$sql_insert ="insert into pulsesensor(value) values ('$value')";
if($sql_insert){
echo "insert successfull";
}
else {
echo "insert failed";
} echo "<br>";
$result = mysql_query($sql_insert);
if($result){
echo "insert successfull";
}
else {
echo "insert failed" . mysql_error($result);
}
?>
and for real-time chart i used this code
<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/exporting.js"></script>
<div id="container" style="min-width: 310px; height: 400px; margin: 0
auto">
</div>
/**
* Request data from the server, add it to the graph and set a timeout
* to request again
*/
function requestData() {
$.ajax({
url: 'mysql0.php',
success: function(point) {
var series = chart.series[0],
shift = series.data.length > 20; // shift if the series is
// longer than 20
// add the point
chart.series[0].addPoint(point, true, shift);
// call it again after one second
setTimeout(requestData, 1000);
},
cache: false
});
}
$(document).ready(function() {
chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
defaultSeriesType: 'spline',
events: {
load: requestData
}
},
title: {
text: 'Live Heartbeats data'
},
xAxis: {
type: 'datetime',
tickPixelInterval: 150,
maxZoom: 20 * 1000
},
yAxis: {
minPadding: 0.2,
maxPadding: 0.2,
title: {
text: 'Value',
margin: 80
}
},
series: [{
name: 'heartbeats data',
data: []
}]
});
});
</script>
at the end the result is this

Dynamically updated data with highstock

I have a MySQL database that gets updated every 5 seconds with a time-stamp and temperature.
I'm trying to represents the live data using high stock.
Here's my code so far:
<?php
$servername = "localhost";
$username = "root";
$password = "*******";
$database = "MicroCSP";
$port = 3306;
header("Content-type: text/html");
$con = new mysqli($servername,$username,$password,$database,$port);
if ($con->connect_error)
{
die("Connection failed: " . $conn->connect_error);
}
$sql="select TimeStamp as time,Pdc2 as temperature from SpotData";
if ($result = $con->query($sql)) {
// $row = mysqli_fetch_array($result, MYSQLI_NUM);
while($row = $result->fetch_array()){
$rows[] = $row;
}
foreach($rows as $row){
$datetime = ($row['time'])*1000;
$temp = $row['temperature'];
$data[] = "[$datetime, $temp]";
}
//$data[] = "[$datetime, $out]";
//echo(json_encode($data));
$result->close();
}
else {
echo "Error: " . $sql . "<br>" . $con->error;
}
$con->close();
?>
<!DOCTYPE html>
<html>
<head>
<title>
Temps Reel
</title>
<script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
<script src="https://code.highcharts.com/stock/highstock.js"></script>
<script src="//code.highcharts.com/stock/modules/exporting.js"></script>
<script>
$(function () {
Highcharts.setOptions({
global : {
useUTC : false
}
});
// Create the chart
$('#container').highcharts('StockChart', {
chart : {
events : {
load : function () {
// set up the updating of the chart each 5 seconds
var series = this.series[0];
setInterval(function () {
var x = <?php echo $datetime; ?>, //<?php echo $datetime; ?> // current time
y = <?php echo $temp; ?>//Math.round(Math.random() * 100);
series.addPoint([x, y], true, true);
}, 5000);
}
}
},
rangeSelector: {
buttons: [{
count: 1,
type: 'minute',
text: '1M'
}, {
count: 5,
type: 'minute',
text: '5M'
}, {
type: 'all',
text: 'All'
}],
inputEnabled: false,
selected: 0
},
title : {
text : 'Live random data'
},
exporting: {
enabled: false
},
series : [{
name : 'Data',
data : [<?php echo join($data, ',') ?>],
}]
});
});
</script>
</head>
<body>
<div id="container" style="height: 400px; min-width: 310px"></div>
</body>
</html>
When I use the built-in date function and random values it works just fine but when I try to echo out data from my database it doesn't work.
Any help?

Loop inside Jquery Chart to make it dynamic

Im new in Js and Jquery and I have a curiosity about the Jquery Chart that is free to download and I want to make the data inside to be coming from the database to make it dynamic but somehow I find it difficult to loop it in.
here is my sample code, I used PHP to get the database and pass it on a JS variable
<!DOCTYPE HTML>
<html>
<head>
<?php
$link = mysqli_connect("localhost","root","","raksquad_centralized") or die("Error " . mysqli_error($link));
if($link->connect_error){
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
$query = "SELECT * FROM raksquad_centralized.grade";
$result = $link->query($query);
$subject_id= array();
$genAve = array();
while($row = mysqli_fetch_array($result)){
$subject_id[] = $row['subject_id'];
$genAve[]= $row['gen_ave'];
}
?>
<script type="text/javascript">
window.onload = function () {
var DataXAxis = <?php echo json_encode($subject_id); ?>; // X axis that corresponds to students
var DataYAxis = <?php echo json_encode($genAve); ?>; // Y axis that corresponds to grades
var chart = new CanvasJS.Chart("chartContainer",
{
title:{
text: "Top Students"
},
animationEnabled: true,
axisY: {
title: "Grades"
},
axisX: {
title: "Students"
},
legend: {
verticalAlign: "bottom",
horizontalAlign: "center"
},
theme: "theme2",
data: [
{
type: "column",
showInLegend: true,
legendMarkerColor: "grey",
legendText: "General Average",
dataPoints: [
//the area to loop with the value of DataXAxis, DataYAxis
{y: 98, label: "MT1234" },
{y: 72, label: "MT1236"} //corresponds to the barcharts
]
}
]
});
chart.render();
}
</script>
<script type="text/javascript" src="./canvasjs.min.js"></script>
</head>
<body>
<div id="chartContainer" style="height: 300px; width: 100%;">
</div>
</body>
</html>
appreciate for the help, useful for learning :)
I just use a php code to fetch the data, then json encode it.
On the script use json parse

Highstock with php and mysql

i want to make chart with mysql database. I have two columns - timestamp and temperature. This is the timestamp format - 2015-06-11 22:45:59 and the temperature is integer. Im not sure that my conversion of timestamp to javascript time is correct i have or maybe i have other mistake. this is my code:
data.php
<?
define('DBHOST','localhost');
define('DBUSER','root');
define('DBPASS','...');
define('DBNAME','diplomna2');
try {
//create PDO connection
$db = new PDO("mysql:host=".DBHOST.";port=3306;dbname=".DBNAME, DBUSER, DBPASS);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
//show error
echo '<p class="bg-danger">'.$e->getMessage().'</p>';
exit;
}
$stmt = $db->query('SELECT * FROM temperature');
$res=array();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$row['timestamp'] = strtotime($row['timestamp']);
$row['timestamp'] *=1000;
echo $res="[".$row['timestamp'] . ',' . $row['temperature'] ."]";
}
?>
this is the output:
[1434051959000,25][1434051969000,26][1434051979000,26][1434051990000,28][1434052000000,27][1434052024000,25][1434052034000,24][1434052044000,23]
html file:
<!DOCTYPE HTML>
<html>
<head>
<script type="text/javascript" src="js/jquery-1.7.1.min.js" ></script>
<script src="http://code.highcharts.com/stock/highstock.js"></script>
<script src="http://code.highcharts.com/stock/modules/exporting.js"></script>
<script type="text/javascript">
$(function() {
$.getJSON('data.php', function(data) {
// Create the chart
$('#container').highcharts('StockChart', {
rangeSelector : {
inputEnabled: $('#container').width() > 480,
selected : 1
},
title : {
text : 'Temperature'
},
series : [{
name : 'temperature',
data : data,
type : 'areaspline',
threshold : null,
tooltip : {
valueDecimals : 2
},
fillColor : {
linearGradient : {
x1: 0,
y1: 0,
x2: 0,
y2: 1
},
stops : [
[0, Highcharts.getOptions().colors[0]],
[1, Highcharts.Color(Highcharts.getOptions().colors[0]).setOpacity(0).get('rgba')]
]
}
}]
});
});
});
</script>
</head>
<body>
<div id="container" style="height: 400px; min-width: 310px"></div>
</body>
</html>
Correct way to make JavaScript understand your PHP array is json_encode()
Change your code block near while to
$res = [];
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$res[] = [ strtotime($row['timestamp'])*1000, $row['temperature'] ];
}
echo json_encode($res);

Categories