Auto Update Highcharts with Ajax - javascript

Hopefully somebody can be of help to me here.
I'm trying to update a graph with information from ajax, I've already confirmed that the ajax is of the correct format etc and the initial graph load works perfectly but it doesn't seem to update correctly.
My code:
$(document).ready(function() {
var options = {
chart: {
renderTo: 'cpuhealth',
type: 'column'
},
title: {
text: 'CPU Usage'
},
yAxis: {
labels: {
formatter: function() {
return this.value + ' %';
}
},
title: {
text: 'Usage (%)'
}
},
xAxis: {
title: {
text: 'CPU Core ID#'
}
},
tooltip: {
formatter: function() {
return 'CPU Core: <b>' + this.x + '</b><br>Usage <b>' + this.y + '%</b>';
}
},
legend: {
enabled: false
},
series: [{}]
};
var chart;
$.getJSON('http://url-to-json-file/index.php', function(jsondata) {
options.series[0].data = JSON.parse(jsondata.cpu);
chart = new Highcharts.Chart(options);
});
window.setInterval(function(){
var chart = new Highcharts.Chart(options);
$.getJSON('http://url-to-json-file/index.php', function(jsondata) {
options.series[0].data = JSON.parse(jsondata.cpu);
});
}, 5000);
});
The JSON is being pulled fine but it just isn't updating the chart every 5 seconds :(
Any help would be greatly appreciated, I'm abit of a novice with JS.

Have you tried,
events: {
load: function() {
// set up the updating of the chart each second
var series = this.series[0];
setInterval(function(){
var chart = new Highcharts.Chart(options);
$.getJSON('http://url-to-json-file/index.php', function(jsondata) {
options.series[0].data = JSON.parse(jsondata.cpu);
});
}, 5000);
}
}
Then your chart data would be,
var options = {
chart: {
renderTo: 'cpuhealth',
type: 'column'
},
title: {
text: 'CPU Usage'
},
events: {
load: function() {
// set up the updating of the chart each second
var series = this.series[0];
setInterval(function(){
var chart = new Highcharts.Chart(options);
$.getJSON('http://url-to-json-file/index.php', function(jsondata) {
options.series[0].data = JSON.parse(jsondata.cpu);
});
}, 5000);
}
},
yAxis: {
labels: {
formatter: function() {
return this.value + ' %';
}
},
title: {
text: 'Usage (%)'
}
},
xAxis: {
title: {
text: 'CPU Core ID#'
}
},
tooltip: {
formatter: function() {
return 'CPU Core: <b>' + this.x + '</b><br>Usage <b>' + this.y + '%</b>';
}
},
legend: {
enabled: false
},
series: [{}]
};

Related

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 bar chart wont animate

Not sure why because I have done it in the past, but I have a Highcharts bar chart and it won't animate. This is the declaration of the chart,
function initializeData() {
$http.get(url).success(function(ret) {
$scope.jsondata = ret;
var newdata = [];
for (x = 0; x < 5; x++) {
newdata.push({
name: setName($scope.jsondata[x].name),
y: $scope.jsondata[x].data[0],
color: getColor($scope.jsondata[x].data[0])
});
}
$scope.chart.series[0].setData(newdata);
});
mainInterval = $interval(updateData, 5000);
}
function updateData() {
$http.get(url).success(function(ret) {
$scope.jsondata = ret;
console.debug("here");
for (x = 0; x < 5; x++) {
$scope.chart.series[0].data[x].update({
y: $scope.jsondata[x].data[0],
color: getColor($scope.jsondata[x].data[0])
});
}
});
}
$scope.chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
type: 'bar',
animation: true,
events: {
load: initializeData
}
},
title: {
text: ''
},
xAxis: {
type: 'category',
labels: {
style: {
fontSize: '11px'
}
}
},
yAxis: {
min: 0,
max: 100,
title: {
text: 'Total Score',
align: 'high'
}
},
legend: {
enabled: false
},
tooltip: {
pointFormat: 'Total Score <b>{point.y:.3f}</b>'
},
series: [{
name: 'Active Users',
data: [],
dataLabels: {
enabled: true,
rotation: 30,
style: {
fontSize: '10px',
fontFamily: 'Verdana, sans-serif'
},
format: '{point.y:.3f}', // one decimal
}
}]
});
And as you can see I have animate : true, so I am not sure what is the problem here. I have this older plunker where all of the data is in separate series, but it animates fine. But this is the plunker I am working on and having trouble with. They are like identical basically. In the newer one I broke out the initialization of data into its own method, but that is the only real main difference.
Some edits:
So as I was saying, I have done things this way with an areaspline chart (I know it was said they work a bit different but they are set up identically).
function initializeData() {
$interval.cancel(mainInterval);
$scope.previousPackets = '';
$http.get("https://api.myjson.com/bins/nodx").success(function(returnedData) {
var newdata = [];
var x = (new Date()).getTime();
for (var step = 9; step >= 0; step--) {
newdata.push([x - 1000 * step, 0]);
}
$scope.chart.series[0].setData(newdata);
});
mainInterval = $interval(updateData, 2000);
}
function updateData() {
$http.get(url + acronym + '/latest').success(function(returnedData) {
var x = (new Date()).getTime();
if ($scope.previousPackets != returnedData[0].numPackets) {
$scope.chart.series[0].addPoint([x, returnedData[0].numPackets], true, true);
$scope.previousPackets = returnedData[0].numPackets;
} else {
$scope.chart.series[0].addPoint([x, 0], true, true);
}
});
}
$scope.chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
type: 'areaspline',
animation: Highcharts.svg, // don't animate in old IE
marginRight: 10,
events: {
load: initializeData
}
},
title: {
text: ''
},
xAxis: {
type: 'datetime',
tickPixelInterval: 150
},
yAxis: {
title: {
text: 'Packets'
},
plotLines: [{
value: 0,
width: 1,
color: '#d9534f'
}]
},
tooltip: {
formatter: function() {
return Highcharts.numberFormat(this.y) + ' packets<b> | </b>' + Highcharts.dateFormat('%H:%M:%S', this.x);
}
},
legend: {
enabled: false
},
exporting: {
enabled: false
},
series: [{
name: 'Packets',
data: []
}]
});
I also updated the first chunk of code with the initializeData() method and updateData() method which are seemingly identical in both different charts.
It looks like it plays an important role if you provide your data at chart initialization or after. For simplicity I refactored your code a little
function initializeChart(initialData, onload) {
$scope.chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
type: 'bar',
animation: true,
events: {
load: onload
}
....
series: [{
name: 'Active Users',
data: initialData,
dataLabels: {
enabled: true,
format: '{point.y:.3f}', // one decimal
}
}]
});
}
function getData(callback) {
$http.get(url).success(function(ret) {
$scope.jsondata = ret;
var newdata = [];
for (x = 0; x < 5; x++) {
newdata.push([setName(ret[x].name), ret[x].data]);
}
callback(newdata);
});
}
As a result your two planks are in essense reduced to two methods below. The first initializes chart with preloaded data and the second updates data in existing chart.
function readDataFirst() {
getData(function(newdata) {
initializeChart(newdata);
});
}
function initializeChartFirst() {
initializeChart([], function() {
getData(function(newdata) {
$scope.chart.series[0].setData(newdata);
})
});
}
The first one animates fine while the second does not. It looks like highcharts skips animation if dataset is not initial and is treated incompatible.
However if you really want to have animation in your current plant (chart first workflow) you can achieve that by initializing first serie with zeros and then with the real data. This case it will be treated as update
function forceAnimationByDoubleInitialization() {
getData(function(newdata) {
initializeChart([]);
var zerodata = newdata.map(function(item) {
return [item[0], 0]
});
$scope.chart.series[0].setData(zerodata);
$scope.chart.series[0].setData(newdata);
});
All these options are available at http://plnkr.co/edit/pZhBJoV7PmjDNRNOj2Uc

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',
...
},
...
});

use getJSON to getData From WebMethod Highcharts Live Data

I ve this graph below that i would like insert data from a WebMethod (WebMethod is in a WebService):
Highcharts.setOptions({
global: {
useUTC: false
}
});
chart3 = new Highcharts.Chart({
credits: {
enabled: false
},
chart: {
renderTo: 'container3',
type: 'spline',
animation: Highcharts.svg, // ne marche pas dans les IE anciens
marginRight: 10,
events: {
load: function() {
// MAJ du chart chaque seconde
var series = this.series[0];
setInterval(function() {
var x = (new Date()).getTime(), // temps
y = Math.random();
series.addPoint([x, y], true, true);
}, 1000);
}
}
},
title: {
text: 'test'
},
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() {
// generation de valeurs aléatoires
var data = [],
time = (new Date()).getTime(),
i;
function onSucess(result) {
alert(result);
}
for (i = -19; i <= 0; i++) {
data.push({
x: time + i * 1000,
y: Math.random()
});
}
return data;
})()
}]
});
In the setInterval part, I d like to get value from a WebService WebMethod and put it in y, :
WebService:[WebMethod]
public int getInt()
{
val2 = rand.Next(1, 100);
return val2;
}
Apparently I need to use GetJSON...
But I dont know how....
Could you help me giving an example please ?

How to parse JSON into HighCharts line graph?

I am trying to parse the following JSON string remotely:
[{"name":"Object1","data":[1,2]},{"name":"Object2","data":[3,4]}]
I am doing so with the following code:
$(function () {
var chart;
$(document).ready(function() {
var options = {
chart: {
renderTo: 'container',
type: 'line',
marginRight: 130,
marginBottom: 25
},
title: {
text: 'hits by time',
x: -20 //center
},
subtitle: {
text: 'Source:',
x: -20
},
xAxis: {
categories: ['8am', '9am', '10am', '11am', '12pm', '1pm',
'2pm', '3pm', '4pm', '5pm', '6pm', '7pm']
},
yAxis: {
title: {
text: 'Hits'
},
plotLines: [{
value: 0,
width: 1,
color: '#808080'
}]
},
tooltip: {
formatter: function() {
return '<b>'+ this.series.name +'</b><br/>'+
this.x +': '+ this.y;
}
},
legend: {
layout: 'vertical',
align: 'right',
verticalAlign: 'top',
x: -10,
y: 100,
borderWidth: 0
},
series: []
};
$.getJSON('http://localhost:8080/jsonget', function(data) {
var series = {
data: []
};
$.each(data, function(i,item){
alert(item.name);
series.name = item.name;
$.each(item.data, function(j,dataitem){
alert(dataitem);
series.data.push(parseFloat(dataitem[i]));
});
});
options.series.push(series);
// Create the chart
var chart = new Highcharts.Chart(options);
});
});
});
The chart does not render, but does so when I substitute the remote portion for the CSV example on the site.
Does anyone know what the problem is?
As far as I can tell your data seems to be well formed. So, this should do it:
var chart;
$.getJSON('http://localhost:8080/UDPver/tagdiscover', function(data) {
// Populate series
options.series = data;
// Create the chart
chart = new Highcharts.Chart(options);
});
The problems is that the chart then is redrawn. So if you have other lines that is disabled (from legend), it will be visible agian when you do a update.
I have 5 lines in my graph. It is updated every second.
From the legend I can disable/remove some of the lines from the graph.
But using this method above (it works) the complete graph is redrawn and all lines is visible again.
Is it possible to just update the series (lines) and not the paramaters?
Like this (not working):
function doAjaxData() {
AjaxLoadingIcon(1);
$.ajax({
url: getAjaxUrl(1),
dataType: 'json',
cache: false,
async: true,
success: function (json) {
AjaxLoadingIcon(0);
gchartOptions.series = [];
gchartOptions.series = json;
// gchart = new Highcharts.Chart(gchartOptions);
gchart.render();
_updateTimer = window.setTimeout("doAjaxData()", 1000);
}
}
});
}
Atma.
You just should write just dataitem instead of dataitem[i] and it will work.
$.each(data, function(i,item){
alert(item.name);
series.name = item.name;
$.each(item.data, function(j,dataitem){
alert(dataitem);
series.data.push(parseFloat(dataitem[i]));
});
});

Categories

Resources