Highcharts live data update does not work - javascript

I am new to js, just copy from official website, the code is:
<html>
<head>
<title>Charts using Socket.io and Highcharts</title>
<script src="https://code.highcharts.com/stock/highstock.js"></script>
<script src="https://code.highcharts.com/stock/modules/exporting.js"> </script>
<script>
$(function () {
Highcharts.setOptions({
global: {
useUTC: false
}
});
// Create the chart
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;
}())
}]
});
});
</script>
</head>
<body>
<div id="container" style="height: 400px; min-width: 310px"></div>
</body>
</html>
the console told me ‘$’ is not defined, and I have tried to get rid of 'function', getting highcharts error #13. I run it on nodejs, and the code is in index.html file, no other js file.

Add this before your current script tags:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
Check this:
https://jsfiddle.net/basmLukr/
Note: $(function () {..} is The jQuery shorter method for the document ready event, so first you need to include jQuery. And I think Highcharts creating/updating should be called after page loaded, That's why It didn't work when you got rid of $(function () {..} which is "page loaded" function.

Related

Render chart only once with multiple events : Highcharts

So what I have is a chart in which I have events function which loads data for multiple sets.
suppose I have data of 3000 points. The first data set renders the first 1000 points and after that second data set renders 2000 points.
for which I am calling my 'events' function .
but the problem arises that after showing the first 1000 set of data. The chart starts from the begining.
I don't want that.
That's why I need a solution so that my Highchart's chart render only once and the event function loads continuously.
Here's a snip of my Highchart's js
Highcharts.chart("chartcontainer", { // make thsi chart load only once.
chart: {
type: 'line',
animation: Highcharts.svg, // don't animate in old IE
marginRight: 10,
//Load this event function as the data updates
events: {
load: function() {
var series = this.series[0],
chart = this;
setInterval(function() {
//some logic regarding the chart
//..
v = {
y: y,
x: x
};
console.log("V value", v);
series.addSeries(v, false, true);
counter++;
localcounter++;
} else
{
oldcounter=counter;
flagToreload=1;
}
}, 1000/130);
setInterval(function() {
chart.redraw(false);
}, 100);
}
}
},
time: {
useUTC: false
},
title: {
text: 'Live random data'
},
xAxis: {
type: 'Value',
gridLineWidth: 1
},
yAxis: {
title: {
text: 'Value'
},
plotLines: [{
value: 0,
width: 1,
color: '#808080'
}],
gridLineWidth: 1
},
tooltip: {
headerFormat: '<b>{series.name}</b><br/>',
pointFormat: '{point.x:%Y-%m-%d %H:%M:%S}<br/>{point.y:.2f}'
},
exporting: {
enabled: false
},
series: [{
animation: false,
name: 'Random data',
data: (function() {
// generate an array of random data
var data = [],
time = counter,
i;
for (i = -1000; i <= 0; i += 1) {
data.push([
counter,
null
]);
}
return data;
}())
}]
});
You can use:
addPoint method:
chart: {
events: {
load: function() {
var newData,
chart = this,
series = chart.series[0];
setInterval(function() {
newData = getRandomData();
newData.forEach(function(el) {
series.addPoint(el, false);
});
chart.redraw();
}, 2000);
}
}
}
Live demo: http://jsfiddle.net/BlackLabel/2a8qswhf/
API Reference: https://api.highcharts.com/class-reference/Highcharts.Series#addPoint
setData method:
chart: {
events: {
load: function() {
var newData,
chart = this,
combinedData,
series = chart.series[0];
setInterval(function() {
newData = getRandomData();
combinedData = series.userOptions.data.concat(newData);
series.setData(combinedData);
}, 2000);
}
}
}
Live demo: http://jsfiddle.net/BlackLabel/Lmsk8yw9/
API Reference: https://api.highcharts.com/class-reference/Highcharts.Series#setData

Highcharts Not displaying function's data values

i Have created a Highchart using the Following Highchart's Demo:
https://www.highcharts.com/demo/dynamic-update
Now What I did I created my Own function to add dynamic values to the Chart.
I created a function to get the dynamic data from a particular php file whose data changes on every page load event.
I am getting the data values in the getData function console.log
Here is the Script That I am using.
<script type="text/javascript">
$(document).ready(function(){
function getData(){
$.ajax({
type: 'GET',
url: 'data.php',
success: function(data){
// var number = document.write(data) ;
console.log(data);
return data ;
}
}) ;
}
Highcharts.chart('chart', {
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 = getData();
console.log(y);
series.addPoint([x, y], true, true);
}, 1000);
}
}
},
time: {
useUTC: false
},
title: {
text: 'Live random data'
},
xAxis: {
type: 'datetime',
tickPixelInterval: 150
},
yAxis: {
title: {
text: 'Value'
},
plotLines: [{
value: 0,
width: 1,
color: '#808080'
}]
},
tooltip: {
headerFormat: '<b>{series.name}</b><br/>',
pointFormat: '{point.x:%Y-%m-%d %H:%M:%S}<br/>{point.y:.2f}'
},
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: getData()
});
}
return data;
}())
}]
});
});
</script>
Now as you can see that I have created a getData function and getting the data value in return.
On console log under the getData function, I am getting integer Value in return every one second.
the problem is that under the Highchart's function, I am not able to get the data values using getData function, it's returning undefined in the console .
Highchart's is running but it does not show any data points. it is moving but without showing any data points.
Please correct me in the area , where I am doing wrong.
Any help is appreciated. Thanks
ajax calls are run asynchronously so you cant really return data from it.
instead you should render chart inside the ajax success function.
A good example is here already.
https://www.highcharts.com/docs/working-with-data/live-data
Basically
1. point on load to call a function getData
2. in Getdata call ajax function.
3. in success of ajax render chart with new data.
document.addEventListener('DOMContentLoaded', function() {
chart = Highcharts.chart('container', {
chart: {
type: '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: []
}]
});
});
/**
* Request data from the server, add it to the graph and set a timeout
* to request again
*/
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
// add the point
chart.series[0].addPoint(point, true, shift);
// call it again after one second - add this if you want to auto refresh
// setTimeout(requestData, 1000);
},
cache: false
});
}

Change Highchart graph amplitude through slider

Complete beginner here.
From Spline updating each second, I wanna change amplitude of graph (it means, the range of random generated number) via slider. How to implement it?
I am able to change variables, but variable y that stands for amplitude is inside a function, and none of my solutions worked unfortunately.
Here is the code
<html>
<head>
<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>
</head>
<body>
<div id="container" style="min-width: 310px; height: 400px; margin: 0 auto"></div>
<script>
$(document).ready(function () {
Highcharts.setOptions({
global: {
useUTC: false
}
});
Highcharts.chart('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 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>
</body>
How to add slider, that can control value of variable y in load?
Thanks in advance.
Refer to this live demo: http://jsfiddle.net/kkulig/4y120nbo/
I placed the reference to the HTML slider in 'higher' scope than load function. I use rangeForm.value to manipulate the amplitude of generated numbers:
// 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() * rangeForm.value;
series.addPoint([x, y], true, true);
}, 1000);

Dyanamic highchart with csv/txt input file

I am new on highchart. I have gone through the help portal of this and I am unable to fulfill my requirement so need you help/guide to complete this task .
My task is to read the data from a csv/TXT file which contains TPS details as per below format and show it on a dynamic running chart ( it's ok if the chart will refresh in one minute ) .
DATA format:
16:08:02,3
16:08:04,5
16:08:05,1
16:09:01,10
The above file is appending on every second , will read the last one minute data from file and plot this on chart .
I have tried this using below code. Don't know what I am missing.
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>TPS Example</title>
<script type="text/javascript" src="C:/Backup/SUNIL/Software/library/jquery-2.2.0.js"></script>
<style type="text/css">
${demo.css}
</style>
<script type="text/javascript">
$(function () {
$(document).ready(function () {
Highcharts.setOptions({
global: {
useUTC: false
}
});
$('#container').highcharts({
chart: {
renderTo: 'container',
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: '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: '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>
</head>
<body>
<script src="C:\Backup\SUNIL\Software\library\Highcharts-4.2.1\js\highcharts.js"></script>
<script src="C:\Backup\SUNIL\Software\library\Highcharts-4.2.1\js\highcharts.js"></script>
<div id="container" style="min-width: 50px; height: 200px; margin: 0 auto"></div>
</body>
</html>
You probably have incorrect paths to your script files.
<script src="C:\Backup\SUNIL\Software\library\Highcharts-4.2.1\js\highcharts.js"></script>
<script src="C:\Backup\SUNIL\Software\library\Highcharts-4.2.1\js\highcharts.js"></script>
The code works fine: http://jsfiddle.net/tmp3pty2/

Javascript,Highcharts : Avoiding parallel function calls

I am developing a dashboard, where there are 5 buttons, and on click of each button, corresponding chart is displayed in the same div.
The structure of my code is as follows :
$(document).ready(function(){
$("button").click(function(){
function requestData() {
$.ajax({
url : ....,
success : function(){
.....
//Real Time Plotting of Data
chart.series[0].addPoint(eval(point), true, shift);
setTimeout(requestData, 2000);
}
});
}
chart = new Highcharts.Chart({
chart: {
renderTo: 'chart',
defaultSeriesType: 'spline'
},
....
....
});
});
});
The Problem : On every click of the button, a parallel requestData() starts, multiple parallel threads run at the same time. This leads in random addPoint and increase in memory consumed.
Also, when checked with Highcharts.Chart in the console, after every click, a undefined objects adds up.
How do I restructure the code for optimum performance ?
Refer the code below, your high chart implement can be like this
$(function () {
$(document).ready(function () {
$('#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;
}())
}]
});
});
});
Basically, you do not need to make your arrangement to live plotting, high chart has this option UPDATE
Refer live fiddle
http://jsfiddle.net/anilk/3u0ng35s/
Replace below data option to your ajax call
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;
}

Categories