Ilya Davydyuk Ilya Davydyuk - 4 months ago 55
Ajax Question

Highcharts live data, json ajax

My head is going to blow.

livedata.php loads json when page open.
live.php add point to graph.

From livedata.php i got output like this:

[["Date.UTC(2016, 07-1, 28, 15, 08)",37],["Date.UTC(2016, 07-1, 28, 15, 08)",37],["Date.UTC(2016, 07-1, 28, 15, 08)",37],["Date.UTC(2016, 07-1, 28, 15, 08)",37],["Date.UTC(2016, 07-1, 28, 15, 08)",37],["Date.UTC(2016, 07-1, 28, 15, 08)",37]]


live.php output - only last row, looks like

["Date.UTC('.2016, 07-1, 29, 15, 40.')", 44]


I've got chart, live addPoint working, but no date on x-axis. What i do wrong?

JS

var chart;

function requestData() {
$.ajax({
url: 'live.php',
success: function(point) {
var series = chart.series[0],
shift = series.data.length > 120; // shift if the series is

chart.series[0].addPoint(eval(point));

setTimeout(requestData, 10000);
},
cache: false
});
}
$(function () {
$.ajax({
url: 'livedata.php',
success: function(point) {
chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
type: 'areaspline',

events: {
load: requestData
}
},
title: {
text: 'Revenue vs. Overhead',

},
subtitle: {
text: '',

},
xAxis: {
type: 'datetime'


},
yAxis: {
title: {
text: 'Amount'
},
plotLines: [{
value: 0,
width: 1,
color: '#808080'
}]
},


series: [{

name: 'Random data',
data: eval(point )
}]
});
},

});


});


live.php

global $dbConnection;
$stmt = $dbConnection->query('SELECT DATE_FORMAT(data,"%Y-%m-%d %H:%i") as dataa, humidity FROM sensorsdata order by id desc limit 1');
$row = $stmt->fetch(PDO::FETCH_ASSOC);
$date_raw = strftime('%Y, %m-1, %d, %H, %M', strtotime($row[dataa]));
$date_complete = "Date.UTC('.$date_raw.')";
$ar = array($date_complete, $row[humidity]);
echo json_encode($ar, JSON_NUMERIC_CHECK);


livedata.php

global $dbConnection;
$stmt = $dbConnection->query('SELECT DATE_FORMAT(data,"%Y-%m-%d %H:%i") as dataa, humidity FROM sensorsdata');

$result = $stmt->fetchAll();

foreach ($result as $row) {
$date_raw = strftime('%Y, %m-1, %d, %H, %M', strtotime($row[dataa]));
$date_complete = 'Date.UTC('.$date_raw.')';
$hum_for_chart[] = [$date_complete, $row[humidity]];

}

echo json_encode($hum_for_chart, JSON_NUMERIC_CHECK);


Chart:
Chart

Answer

I think its problem of your data try to make string like,

live.php

....
$date_complete = "Date.UTC('.$date_raw.')";
$ar = "[".$date_complete.",". $row[humidity]."]";
echo json_encode($ar); 

livedata.php

....
foreach ($result as $row) {
    $date_raw = strftime('%Y, %m-1, %d, %H, %M', strtotime($row[dataa]));
    $date_complete = 'Date.UTC('.$date_raw.')';
    $hum_for_chart[] = "[".$date_complete.",". $row[humidity]."]";
}
....

You can refer highcharts-data-series-issue-with-ajax-json-and-php

Comments