Variable from php to realtime graph javascript - javascript

I have a realtime graph in JS and i want to take every time the last value from my db.
JS file is this.
jQuery(function () {
jQuery(document).ready(function () {
enter code here
Highcharts.setOptions({
global: {
useUTC: false
}
});
$('#cont1').highcharts({
chart: {
type: 'spline',
animation: Highcharts.svg, // don't animate in old IE
marginRight: 10,
events: {
load: function () {
// set up the updating of the chart each second
var series = this.series[0];
var mydata;
setInterval(function () {
myData= php file!
var x = (new Date()).getTime(), // current time
y = myData;
series.addPoint([x, y], true, true);
}, 3000);
}
}
},
title: {
text: 'AirFlow'
},
xAxis: {
type: 'datetime',
tickPixelInterval: 150
},
yAxis: {
title: {
text: 'Value'
},
plotLines: [{
value: 0,
width: 1,
color: '#808080'
}]
},
tooltip: {
formatter: function () {
return '<b>' + this.series.name + '</b><br/>' +
Highcharts.dateFormat('%Y-%m-%d %H:%M:%S', this.x) + '<br/>' +
Highcharts.numberFormat(this.y, 2);
}
},
legend: {
enabled: false
},
exporting: {
enabled: false
},
series: [{
name: 'Random data',
data: (function () {
// generate an array of random data
var data = [],
time = (new Date()).getTime(),
i;
kl = 0
for (i = -19; i <= 0; i += 1) {
data.push({
x: time + i * 1000,
y: kl
});
}
return data;
}())
}]
});
});
});
PHP file is :
<?php
/* Open connection to MySQL database. */
$mysqli = new mysqli("localhost", "root", "", "health_care");
/* Check the connection. */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
/* Fetch result set from table */
$data=mysqli_query($mysqli,"SELECT AirFlow FROM health ORDER BY ID DESC LIMIT 1");
$info=mysqli_fetch_array($data);
echo $info['AirFlow'];
?>
JS file is a real time graph that run in a html file.
I try to put the php code inside JS file but load it only one time and if new variable come to DB no take it!
Thanks a lot!

Related

In highcharts,series without dynamic data does not shift

In the combination of series with and without dynamic data,the series with dynamic data can be easily shifted but where as the other series which are not dynamic do not get shifted out completely.
I have reproduced the issue in the following link: https://jsfiddle.net/8uxepk21/
Here as you can see there are two series. The series with static data appears to be shifting but if you increase the size of the rang-selector,then the series with static data do not get shifted out of the chart completely but still stays unlike the other series.
Is there any option to shift data explicitly without using series.addpoint() method.
I have used series.data[0].remove() and it obviously works fine but when a new data has to arrive for the same series after some time,this remove() method would remove the arriving point aswell. Further if I provide any condition for the maximum points to be in series while shifting,even then it will cause performance issue.
EXPECTED RESULT: Both the series data have to be shifted completely irrespective of the data being static or dynamic.
// Create the chart
Highcharts.stockChart('container', {
chart: {
events: {
load: function () {
// set up the updating of the chart each second
var series1 = this.series[0];
setInterval(function () {
var x = (new Date()).getTime(), // current time
y = Math.round(Math.random() * 100);
series1.addPoint([x, y], true, true);
}, 2000);
var series2 = this.series[1];
//setInterval(function () {
//var x = (new Date()).getTime(), // current time
// y = Math.round(Math.random() * 50);
//series2.addPoint([x, y], true, true);
//}, 2000);
}
}
},
time: {
useUTC: false
},
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
},
legend: {
enabled: true
},
plotOptions: {
series: {
marker: {
states: {
hover: {
enabled: true,
animation: {duration: 100},
enableMouseTracking: true,
stickyTracking: true
}
}
}
}
},
tooltip:{
shared: true,
split: false,
stickyTracking: true,
enableMouseTracking: true,
enabled: true,
followPointer: true,
followTouchMove: true,
formatter: function(){
var tooltip = "";
var phaseNameList = "";
//tooltip += "<b>I-unit "+ "<br/>"+ "x: "+this.x +"</b>";
tooltip += "<b>I-unit "+ "<br/>"+ "x: "+ new Date(this.x)+
"</b>";
tooltip += "<br/>"+ "y: "+this.y +"</b>";
tooltip += "<br/>"+ this + "</b>";
return tooltip;
}
},
series: [{
name: 'Random data1',
data: (function () {
// generate an array of random data
var data = [],
time = (new Date()).getTime(),
i;
for (i = -90; i <= 0; i += 1) {
data.push([
time + i * 1000,
Math.round(Math.random() * 100)
]);
}
return data;
}())
},
{
name: 'Random data2',
data: (function () {
// generate an array of random data
var data = [],
time = (new Date()).getTime(),
i;
for (i = -90; i <= 0; i += 1) {
data.push([
time + i * 1000,
Math.round(Math.random() * 50)
]);
}
return data;
}())
}]
});
<script src="https://code.highcharts.com/stock/highstock.js"></script>
<script src="https://code.highcharts.com/stock/modules/exporting.js"></script>
<script src="https://code.highcharts.com/stock/modules/export-data.js"></script>
<div id="container" style="height: 400px; min-width: 310px"></div>
To achieve it you can add points with null values to the second series. Check the code and demo posted below.
Code:
chart: {
events: {
load: function() {
var chart = this,
series1 = chart.series[0],
series2 = chart.series[1],
x, y;
setInterval(function() {
x = (new Date()).getTime();
y = Math.round(Math.random() * 100);
series1.addPoint([x, y], false, true);
series2.addPoint([x, null], false, true);
chart.redraw();
}, 2000);
}
}
}
Demo:
https://jsfiddle.net/BlackLabel/6vp5cbt8/

Bind highstock(highcharts) to live data?

I am using .net core 2.0 web socket to generate some data. I want to send the data to this chart and draw the chart.
In the code below I want to show the live data without default values. I tried a lot but I wasn't successful. If I remove default value from 'series', chart will disappear. IS that possible to draw this chart on the fly?
Highcharts.setOptions({
global: {
useUTC: false
}});
Highcharts.stockChart('container', {
chart: {
events: {
load: function () {
// set up the updating of the chart each second
var series = this.series[0];
setInterval(function () {
var x = (new Date()).getTime(), // current time
y = Math.round(Math.random() * 100);
series.addPoint([x, y], true, true);
}, 1000);
}
}
},
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: 'Random data',
data: (function () {
// generate an array of random data
var data = [],
time = (new Date()).getTime(),
i;
for (i = -999; i <= 0; i += 1) {
data.push([
time + i * 1000,
Math.round(Math.random() * 100)
]);
}
return data;
}())
}]});
Finally I could find the solution. I needed to add xAxis property to my chart. By adding the code below, problem solved. Now it starts from current time.
xAxis: {
type: 'datetime',
tickPixelInterval: null,
maxZoom: 10 * 1000,
min: new Date().getTime()
}

How-to Dynamic update a chart via socket.io and slide chart view as a sliding window?

Could anyone help me to figure out what I am missing on showing only last X samples in the chart, please?
Looking at this example and this thread, I am developing a simple page which receives samples from server via socket.io and plots the last 10 samples.
However, it is not working and I am struggling to figure out what I am missing.
The server.js is a simple samples generator:
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.get('/', function (req, res) {
res.sendfile('index.html');
});
// On connection event.
io.on('connection', function (socket) {
console.log('a user connected');
socket.on('disconnect', function () {
console.log('user disconnected');
// TODO (How-to) release connection (?)
});
var max = 100; // Scale samples from 0 to 100.
// Generate random samples.
setInterval(function () {
var x = (new Date()).getTime(), // current time
y = Math.floor((Math.random() * max) + 1);
socket.emit('chart_data', {
x: x,
y: y
});
console.info("emitted: [" + x + "," + y + "]");
}, 2000); //update every sec.
});
http.listen(3000, function () {
console.log('listening on *:3000');
});
The html file include such script to handle the plot:
$(function() {
Highcharts.setOptions({
global: {
useUTC: false
}
});
// Instantiate the chart object which plots the samples.
var graph = new Highcharts.chart('graph_container', {
chart: {
type: 'spline',
animation: Highcharts.svg, // don't animate in old IE
marginRight: 10,
events: {
load: function () {
// set up the updating of the chart on each sample
var series = this.series[0];
socket.on('chart_data', function (sample) {
//add chart data to series
series.addPoint([sample.x, sample.y], true, false);
});
}
}
},
title: {
text: 'Live random data'
},
xAxis: {
type: 'datetime',
tickPixelInterval: 150
},
yAxis: {
title: {
text: 'Value'
},
plotLines: [{
value: 0,
width: 1,
color: '#808080'
}]
},
tooltip: {
formatter: function () {
return '<b>' + this.series.name + '</b><br/>' +
Highcharts.dateFormat('%H:%M:%S', this.x) + '<br/>' +
Highcharts.numberFormat(this.y, 2);
}
},
legend: {
enabled: false
},
exporting: {
enabled: false
},
series: [{
name: 'Random data',
data: (function () {
// generate an array of random data
var data = [],
time = 0,
i;
socket.on('chart_data', function (sample) {
//add chart data to series
time = sample.x;
for (i = -19; i <= 0; i += 2) {
data.push({
x: time + i
});
}
});
return data;
}())
}]
});
});
I am brand new to node.js, but I believe that my mistake is pushing samples without y in "data.push". However, the plot is working, but without the "sliding window" of last X samples (e.g. 10).
Does anyone have a suggestion to let the "sliding window" work, please?
You should emit two events - one with the data initialisation e.g. sample of 10 points, and the second - a point fetching in time interval.
You should not initialise the data in a way you do in the line series.data = (function () ... Instead move the initialisation on load event and use series.setData.
Your series should look like this:
series: [{
name: 'Random data',
data: []
}]
and the load event like this:
events: {
load: function () {
var series = this.series[0];
var socket = io.connect('http://localhost:3000');
socket.on('chart_data_init', function (sample) {
series.setData(sample.data);
});
socket.on('chart_data', function (sample) {
//add chart data to series
series.addPoint([sample.x, sample.y], true, false);
});
}
}
Then modify your server file, you need to add chart_data_init emission with some initialised data
var initData = (function () {
var data = [], i = 0, time = new Date().getTime() - 2000 * 10;
for (; i < 10; i++) {
data.push({
x: time + i * 2000,
y: Math.floor((Math.random() * max) + 1)
});
}
return data;
})();
socket.emit('chart_data_init', {
data: initData
});
You have to have data sorted in ascending order - otherwise Highcharts will not render the data correctly.
Files
index.html
<html>
<head>
<script src="http://localhost:3000/socket.io/socket.io.js"></script>
<script src="http://code.highcharts.com/highcharts.js"></script>
</head>
<body>
<div id="graph_container" style="min-width: 400px; height: 400px; margin: 0 auto"></div>
<script>
// Instantiate the chart object which plots the samples.
console.log
var graph = new Highcharts.chart('graph_container', {
chart: {
type: 'spline',
animation: Highcharts.svg, // don't animate in old IE
marginRight: 10,
events: {
load: function () {
// set up the updating of the chart on each sample
var series = this.series[0];
var socket = io.connect('http://localhost:3000');
socket.on('chart_data_init', function (sample) {
series.setData(sample.data);
});
socket.on('chart_data', function (sample) {
//add chart data to series
series.addPoint([sample.x, sample.y], true, false);
});
}
}
},
title: {
text: 'Live random data'
},
xAxis: {
type: 'datetime',
tickPixelInterval: 150
},
yAxis: {
title: {
text: 'Value'
},
plotLines: [{
value: 0,
width: 1,
color: '#808080'
}]
},
tooltip: {
formatter: function () {
return '<b>' + this.series.name + '</b><br/>' +
Highcharts.dateFormat('%H:%M:%S', this.x) + '<br/>' +
Highcharts.numberFormat(this.y, 2);
}
},
legend: {
enabled: false
},
exporting: {
enabled: false
},
series: [{
name: 'Random data',
data: []
}]
});
</script>
</body>
</html>
server.js
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.get('/', function(req, res){
res.sendfile('index.html');
});
io.sockets.on('connection', function (socket) {
console.log('a user connected');
socket.on('disconnect', function () {
console.log('user disconnected');
// TODO (How-to) release connection (?)
});
var max = 100; // Scale samples from 0 to 100.
var initData = (function () {
var data = [], i = 0, time = new Date().getTime() - 2000 * 10;
for (; i < 10; i++) {
data.push({
x: time + i * 2000,
y: Math.floor((Math.random() * max) + 1)
});
}
return data;
})();
socket.emit('chart_data_init', {
data: initData
});
// Generate random samples.
setInterval(function () {
var x = (new Date()).getTime(), // current time
y = Math.floor((Math.random() * max) + 1);
socket.emit('chart_data', {
x: x,
y: y
});
console.info("emitted: [" + x + "," + y + "]");
}, 2000); //update every sec.
});
http.listen(3000, function(){
console.log('listening on *:3000'); //jalankan server di port 3000
});

reading data from CSV and show continuous graph

I am trying to plot a chart which will read a data from csv file which is appending on every minute with latest data as per below format.
The chart will continue reading data from csv file and show the graph on every second wise. Can you please help me on this? I want to show the exact time which are coming from file should be show on graph.
CSV format..
time,count
18:01:00,3
18:01:01,4
....
$(document).ready(function () {
var csv = [],
x;
Highcharts.setOptions({
global: {
useUTC: false
}
});
var data = 'time,count\n18:01:00,3\n18:01:01,4';
//$.get('data.csv', function(data) {
var lines = data.split('\n');
$.each(lines, function(lineNo, line) {
if(lineNo > 0) {
var items = line.split(',');
useUTC: false;
x = items[0].split(':');
csv.push([Date.UTC(2015,1,1,x[0],x[1],x[2]), parseFloat(items[1])]);
}
});
console.log(csv);
$('#container').highcharts({
chart: {
renderTo: 'container',
type: 'spline',
animation: Highcharts.svg, // don't animate in old IE
marginRight: 10,
useUTC: false,
events: {
load: function () {
// set up the updating of the chart each second
var series = this.series[0];
setInterval(function () {
var l = series.data.length - 1,
lastX = series.data[l].x;
$.get('data.csv', function(data) {
var lines = data.split('\n'),
len = lines.length,
items = lines[len - 1].split(','),
x = items[0].split(':'),
y = parseFloat(items[1]);
useUTC: false;
x = Date.UTC(2015,1,1,x[0],x[1],x[2]);
if(x !== lastX) {
series.addPoint([x, y], true, true);
}
});
}, 1000); //refresh each 1 second
}
}
},
title: {
text: 'TPS Data'
},
xAxis: {
type: 'datetime',
tickPixelInterval: 150
},
yAxis: {
title: {
text: 'Value'
},
plotLines: [{
value: 3,
width: 1,
color: '#808080'
}]
},
tooltip: {
formatter: function () {
return '<b>' + this.series.name + '</b><br/>' +
Highcharts.dateFormat('%H:%M:%S', this.x) + '<br/>' +
Highcharts.numberFormat(this.y, 2);
}
},
legend: {
enabled: false
},
exporting: {
enabled: false
},
series: [{
name: 'Count',
data: csv
}]
});
//});
});
div {
min-width: 50px;
height: 200px;
margin: 0 auto;
}
<script type="text/javascript" src="http://code.jquery.com/jquery-1.12.0.js"></script>
<script type="text/javascript" src="http://code.highcharts.com/highcharts.js"></script>
<div id="container" style=""></div>
Note In the snippet I was replace the ajax function $.get with hardcoded data so it will show the result but the question is about the ajax way.

Highcharts in Laravel 4 project are not displayed

I'm new in Laravel, so I'm still facing problems whenever I try to add js functions to my code.
I need to add a highchart to my laravel project. As a beginning, I just copied the code of one of the charts available on highcharts.com and pasted it in the main view, but nothing is being displayed.
When I added the same code to a normal html file, the graph was displayed normally.
Here's my javascript code
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script src="http://code.highcharts.com/highcharts.js"></script>
<script type="text/javascript">
$(function () {
$(document).ready(function () {
Highcharts.setOptions({
global: {
useUTC: false
}
});
$('#container').highcharts({
chart: {
type: 'spline',
animation: Highcharts.svg, // don't animate in old IE
marginRight: 10,
events: {
load: function () {
// set up the updating of the chart each second
var series = this.series[0];
setInterval(function () {
var x = (new Date()).getTime(), // current time
y = Math.random();
series.addPoint([x, y], true, true);
}, 1000);
}
}
},
title: {
text: 'Live random data'
},
xAxis: {
type: 'datetime',
tickPixelInterval: 150
},
yAxis: {
title: {
text: 'Value'
},
plotLines: [{
value: 0,
width: 1,
color: '#808080'
}]
},
tooltip: {
formatter: function () {
return '<b>' + this.series.name + '</b><br/>' +
Highcharts.dateFormat('%Y-%m-%d %H:%M:%S', this.x) + '<br/>' +
Highcharts.numberFormat(this.y, 2);
}
},
legend: {
enabled: false
},
exporting: {
enabled: false
},
series: [{
name: 'Random data',
data: (function () {
// generate an array of random data
var data = [],
time = (new Date()).getTime(),
i;
for (i = -19; i <= 0; i += 1) {
data.push({
x: time + i * 1000,
y: Math.random()
});
}
return data;
}())
}]
});
});
});
</script>
and the html code
<div id="container" style="width:100%; height:400px;"></div>
Any suggestions how to display the graph?
Thanks in advance.
I think the problem is with the syntax you are creating the chart with: $('#container').highcharts...
It seems highcharts function is not defined using laravel.
There is another way that you can try:
var chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
...
},
...
});

Categories

Resources