Wednesday 18 September 2013

Automatically updating Highcharts with Mysql values

Automatically updating Highcharts with Mysql values

I'm going to be honest, jquery isn't my strong point. What I'm trying to
do is update the graph every second and use the animation of the graph to
update with any changes using the data from the mysql database. I have
been trying to do this with ajax but have yet to be able to get the graph
to generate any proper values. Here is what I have been able to get from
searching through the internet (and stackoverflow obviously).
PHP:
$sql = "SELECT timeDate, value FROM table ORDER BY id DESC LIMIT 1";
$query = mysql_query($sql)or die(mysql_error());
$row = mysql_fetch_array($query);
$x = $row['timeDate']; //I have also tried strtotime($row['timeDate'])
//timeDate format is 2004-04-04 02:00:00
$y = intval($row['value']); //Prints 20
$arrayTest = array($x, $y);
echo json_encode($arrayTest);
JQUERY:
<script type="text/javascript" src="libs/highcharts.js" ></script>
<script type="text/javascript" src="libs/themes/gray.js"></script>
<script type="text/javascript">
var chart;
function requestData() {
$.ajax({
url: 'databaseProxy.php',
success: function(point) { //point = "['2004-04-04 02:00:00',20]"
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: 'cellsTest',
type: 'spline',
height: 500,
marginRight: 25,
marginBottom: 25,
marginLeft: 80,
events: {
load: requestData
}
},
title: {
text: 'Live random data'
},
xAxis: {
type: 'datetime',
tickPixelInterval: 100,
maxZoom: 20 * 1000
},
yAxis: {
minPadding: 0.2,
maxPadding: 0.2,
title: {
text: 'Value',
margin: 80
}
},
series: [{
name: 'Random data',
data: []
}]
});
});
</script>
Just to be clear, the graph does appear, it simply doesn't have any
points. When it is running I see a random curved line that keeps changing
even when the values don't change. I don't really know what to make of it.
Also the values in the database are expected to change every second which
is why I want the graph to do the same.
Sorry if this is just a really simple fix, It's a little beyond me given
the current deadline and my amount of time to work on it. I have spent the
past three days trying to figure out how it all works and really I'm not
any closer.

No comments:

Post a Comment