user259584 user259584 - 4 months ago 174
MySQL Question

Live data with highcharts

i'm trying to retrieve live data from mysql database and display it with highcharts but something seems to be wrong because all i get is an empty chart

here's my code



<!DOCTYPE html>
<html>
<head>
<title>Live Messages</title>
<script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
<script src="//code.highcharts.com/highcharts.js"></script>

<script>
var chart;
var dataSource = 'http://localhost/live/data.php?format=json';

function requestData() {
$.ajax({
url: dataSource,
success: function(points) {

chart.series[0].setData(
points,
true
);

// refresh after X miliseconds
setTimeout(requestData, 1000);
},
cache: false
});
}



$(document).ready(function() {

//add our div for the chart
$("#container").append("<div id=chart-trend></div>");

chart = new Highcharts.Chart({
chart: {
renderTo: 'chart-trend',
defaultSeriesType: 'spline',
events: {
load: requestData()
},
animation: {
duration:1000
}
},
title: {
text: 'temperateur'
},
subtitle: {
text: 'past 24 hours'
},
xAxis: {
type: 'datetime',
title: {
text: 'date'
}
},
yAxis: {
title: {
text: 'temp',
margin: 10
}
},
series: [{
showInLegend: false,
data: [],
// pointInterval: 3600*1000 / minute
}]
}); //end chart

}); //end document.ready



</script>
</head>
<body>
<div id="container"></div>
</body>
</html>





and here is the database connection


<?php


/*
Get data from the mysql database and return it in json format
*/


//setup global vars

$format = $_GET['format'];

if($format=='json'){
header("Content-type: text/json");
}

$db = new mysqli('localhost', 'root', '', 'hicharts', 3306);

if (mysqli_connect_error()) {
die('Connect Error (' . mysqli_connect_errno() . ') '
. mysqli_connect_error());
}


// get data
$sql = "select dat,temp from temperateur";


if ($result = $db->query($sql)) {


// $row = mysqli_fetch_array($result, MYSQLI_NUM);

while($row = $result->fetch_array()){
$rows[] = $row;
}

foreach($rows as $row){

$datetime = strtotime($row['dat'])*1000;

$temp = (int)$row['temp'];

$data[] = array($datetime, $temp);
}

echo(json_encode($data));

$result->close();

} else {
echo "Error: " . $sql . "<br>" . $db->error;
}

$db->close();
?>





any help

Answer

I am assuming that your PHP functions work and getting the data you want from the front-end.

First, remove () at events: {load: requestData()}. It should be events: {load: requestData}.

Second, requestData() is called while instantiating Highcharts. At the same time you are setting chart.series[0].setData(points, true); in requestData() function but you can't do that without creating the chart object first.

Try this:

if (typeof chart !== 'undefined') {
  chart.series[0].setData(points,true);
}

You can check this out https://jsfiddle.net/kwqjv5b6/

Comments