csv live data highchart - javascript

My data won't display proper.
I have this kind of data: "1456135353.000000|5424492576222277|8156610153681827"
"1456135353" is for the time.
"5424492576222277" is for the first X
"8156610153681827" is for the second X
This is my code:
var chart
/**
* Request data from the server, add it to the graph and set a timeout
* to request again
*/
function requestData () {
$.ajax({
url: 'api/chart',
dataType: 'text',
success: function (point) {
var series = chart.series[0].push
// longer than 20
// add the point
chart.series[0].addPoint(point, true)
// call it again after one second
setTimeout(requestData, 1000)
},
cache: false
})
}
$(document).ready(function () {
chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
defaultSeriesType: 'line',
events: {
load: requestData
}
},
title: {
text: 'XSnews Graph'
},
xAxis: {
type: 'datetime',
tickPixelInterval: 150,
maxZoom: 20 * 1000
},
yAxis: {
gridLineColor: '#197F07',
gridLineWidth: 1,
title: {
text: 'GB',
margin: 80
}
},
series: [{
name: 'Time',
data: []
}]
})
})
I am not familiar with Highcharts so I have no clue what I am doing wrong.
Do I need to parse it?

You need to parse your data first, before adding a point. Something like this:
success: function (point) {
var options = point.split("|"),
x = parseFloat(options[0]) * 1000,
y_1 = parseFloat(options[1]),
y_2 = parseFloat(options[2]);
chart.series[0].addPoint([x, y_1], true);
setTimeout(requestData, 1000)'
}

Related

How to poll data using Ajax request?

I am trying to poll my data in HighCharts. The graph in this link is what I am trying to achieve. I am using Ajax request to retrieve my data. Here is my code:
setInterval(RefreshGraph, 3000);
...
...
function RefreshGraph() {
var options = {
chart: {
type: 'spline'
},
title: {
text: 'Text'
},
xAxis: {
title: {
text: 'TIMEFRAME'
},
categories: ['-4m', '-3m', '-2m', '-1m', 'Now']
},
yAxis: {
title: {
text: 'NUMBER'
},
},
tooltip: {
crosshairs: true,
shared: true
},
plotOptions: {
spline: {
marker: {
radius: 4,
lineColor: '#666666',
lineWidth: 2
}
}
},
series: [{}]
};
Highcharts.ajax({
url: "/Home/GetData",
success: function (data) {
var formattedData = FormatData(data);
//Graph 1
options.series[0] = formattedData[0];
//Graph 2
options.series[1] = formattedData[1];
Highcharts.chart("container", options);
}
});
}
However, the entire graph gets redrawn with my above code. How can I enable live polling for the above code?
You create a chart every time data is received. You need to create a chart and then update it. Example:
const options = {...};
const chart = Highcharts.chart("container", options);
function RefreshGraph() {
Highcharts.ajax({
url: "/Home/GetData",
success: function(data) {
var formattedData = FormatData(data);
chart.update({
series: [formattedData[0], formattedData[1]]
});
}
});
}
setInterval(RefreshGraph, 3000);
Live demo: http://jsfiddle.net/BlackLabel/6d5stjab/
API Reference: https://api.highcharts.com/class-reference/Highcharts.Chart#update

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()
}

Highcharts load data from server ok, but not updating

I load succesfully from database but then it doesn't update dynamic. The function InitHighchart produce Highchart and I am trying to update series using requestData function
function requestData() {
$.ajax({
url: 'http://....url.../json.php',
data: {region:region},
type: 'post',
dataType: 'json',
error: function (point) {
var series = chart.series[0],
shift = series.data.length > 50; // shift if the series is longer than 20
var values = eval(point);
chart.series[0].addPoint([values[0], values[1]], true, shift);
chart.series[1].addPoint([values[0], values[2]], true, shift);
// call it again after defined seconds
setTimeout(requestData, 1000);
},
success: function (point) {
var series = chart.series[1],
shift = series.data.length > 50; // shift if the series is longer than 20
// add the point
// chart.series[0].addPoint(eval(point), true, shift);
var values = eval(point);
chart.series[0].addPoint([values[0], values[1]], true, shift);
chart.series[1].addPoint([values[0], values[2]], true, shift);
// call it again after defined seconds
setTimeout(requestData, 1000);
},
cache: false
});
}
and here the chart
<!-- 2. Add the JavaScript to initialize the chart on document ready -->
<script>
//is it right here to define chart?
var chart; // global
var region = "<?php Print($region); ?>";
function requestData() {
$.ajax({
url: 'http://cstation.admie.gr/iREACT_cSTATION_WEB/trexousa_katastasi/json.php',
data: {region:region},
type: 'post',
dataType: "json",
error: function (point) {
var series = chart.series[0],
shift = series.data.length > 50; // shift if the series is longer than 20
var values = eval(point);
chart.series[0].addPoint([values[0], values[1]], true, shift);
chart.series[1].addPoint([values[0], values[2]], true, shift);
// call it again after defined seconds
setTimeout(requestData, 1000);
},
success: function (point) {
var series = chart.series[1],
shift = series.data.length > 50; // shift if the series is longer than 20
// add the point
// chart.series[0].addPoint(eval(point), true, shift);
var values = eval(point);
chart.series[0].addPoint([values[0], values[1]], true, shift);
chart.series[1].addPoint([values[0], values[2]], true, shift);
// call it again after defined seconds
setTimeout(requestData, 1000);
},
cache: false
});
}
function InitHighChart()
{
$("#chart1").html('LOADING');
var options =
{
chart: {
renderTo: 'chart1',
borderColor: '#a1a1a1',
borderRadius: 13,
alignTicks: false,
zoomType: 'xy',
height: 700,
events : {
load :requestData()
}
},
credits: {
enabled: false
},
title: {
text: "",
x: -50
},
xAxis: {
series: [{}],
labels: {
rotation: -75
}
},
yAxis: [{ //Primary yAxis
labels: {
format: '{value}',
style: {
color: "#000000"
}
},
title: {
text: '',
style: {
color: "#0B0EED"
}
}
}
],
tooltip: {
formatter: function() {
var s = '<b>'+ this.x +'</b>';
$.each(this.points, function(i, point)
{
s += '<br/>'+point.series.name+': '+point.y;
});
return s;
},
shared: true
},
series: [{},{}]
};
//ajax call
$.ajax({
url: "http://...url.../json1.php",
data: {region:region},
type:'post',
dataType: "json",
success: function(data)
{
options.xAxis.categories = data.datetime;
options.series[0].name = 'Συνολικό Φορτίο (MWatt)';
options.series[0].data = data.SD_PData;
options.series[0].color = "#05A43C";
options.series[1].name = 'Συνολικό Φορτίο Φαινομένου (MVar)';
options.series[1].data = data.SD_MVAData;
options.series[1].color = "#EC2E03";
var chart = new Highcharts.Chart(options);
},
});
}
</script>
<!-- 3. Add the container -->
<div id="chart1" style="width: 1200px; height: 700px; margin: 0 auto"><body onload="InitHighChart()"></div>
Try this out. I have done the same thing in one of my code.
var options = {
chart: {
renderTo: 'chart',
defaultSeriesType: 'column'
},
title: {
text: 'Voting Results'
},
xAxis: {
categories: []
},
yAxis: {
title: {
text: 'votes'
}
},
series: [{}]
};
$.getJSON('votecount2.php', function(data) {
options.series[0].name = "Votes";
options.series[0].data = data;
var chart = new Highcharts.Chart(options);
});
My JSON is this
[["Waseem Akhtar",5],["Imran Ismail",4],["Qaim Ali Shah",4]]

HighCharts : Tooltips exist but line is not drawn in the chart

I met with a problem on HighCharts.
I had to gather data from a xml content with ajax in order to draw it in a HighCharts chart.
I get my datas. I can see my points when I move my mouse over it but my chart is not displaying anything.
A picture to see the problem :
mouse over the third point
And some parts from my code if it can help :
var myData=[];
function makeChart() {
var chart;
$(document).ready(function () {
chart = new Highcharts.Chart({
chart: {
renderTo: 'container2',
type: 'spline',
borderColor: '#DC143C',
borderRadius: 20,
borderWidth: 2,
marginRight: 130,
marginBottom: 25
},
title: {
text: ''
},
xAxis: {
categories :[0,1,2,3,4,5]
},
yAxis: {
title: {
text: 'Values'
},
},
series: [{
color: '#FF00FF',
name: '',
data: myData
}]
});
});
}
$(function (){
$(document).ready(function ping(){
ChartDeOuf();
makeChart();
$.ajax({
type: "GET",
url: 'http://localhost:8080/SASI/runSimulation',
dataType: "xml",
success: function(result){
var i = 0;
var xmlDoc = $.parseXML(result);
var chart = $('#container2').highcharts();
$result = $(xmlDoc);
$(result).find('measure').each(function(){
var $value = $(this);
var attr = $value.attr("meanValue");
myData[i]=attr;
var html = '<p> '+myData[i]+'</p>';
chart.series[0].addPoint({y: myData[i]},false);
chart.redraw();
$('body').append($(html));
i++;
})
},
error: function(result){
alert('timeout/error');
}
});
});
});
Thanks for reading.
Got it, that line saved everything :
myData[i]=parseFloat(attr);

How to add multiple series dynamically and update its data dynamically

my task is to add series dynamically and keep updating their data, which is received by ajax calls.
i know series can be added dynamically by declaring highchart funciton global. and using series.addseries() function , and also data can be updated by using settimout request to ajax call and updating points by using series.addpoint() function.
i have done both the work separably. but when i combine both the technique, data is not added to highchart. i have done lot of research on this, and i am not finding reason for not adding the data. infact script hang the browser.
i have checked the series object, which show x-data and y-data are processed. only difference i find is isDirty field and isDirtydata field are set to true. dont know the reason.
here is the full code
var serverUrl = 'http://'+window.location.hostname+':8000'
Highcharts.setOptions({
global: {
useUTC: false
}
});
data={}
$(document).ready(function(){
$(function () {
console.log("highcharts")
$('#first').highcharts({
chart: {
type: 'spline',
//marginRight: 150,
marginBottom: 5,
events: {
load: requestData(data)
}
},
title: {
text: 'Server Monitroting Tool'
},
subtitle: {
text: 'Cpu usage, Memory Usage,Disk Usage,Mongo Usage'
},
xAxis: {
type: 'datetime',
categories: ['TIME'],
dateTimeLabelFormats : {
hour: '%I %p',
minute: '%I:%M %p'
}
},
yAxis:{
showEmpty:false
},
legend:
{
backgroundColor: '#F5F5F5',
layout: 'horizontal',
floating: true,
align: 'left',
verticalAlign: 'bottom',
x: 60,
y: 9,
shadow: false,
border: 0,
borderRadius: 0,
borderWidth: 0
},
series: {}
});
});
from_date=new Date().getTime()-60000;
function requestData(data)
{
if(!data)
{
console.log("default ")
}
else
{
console.log("requesting")
$.ajax({
url:serverUrl+'/api/fetch_params/',
type:'GET',
data:data,
success:function(response)
{
console.log("in success")
//data = {'type':TypeOfParameter,'hostname':hostname,'sub-type':sub_type,'param':sub_type_parameter,'from-date':from_date}
var id=data['sub-type']+data['param']
var series = chart.get(id)
shift = series.data.length > 100; // shift if the series is longer than 300 (drop oldest point)
response= $.parseJSON(response)
var x=data['sub-type']
all_data=response.response.data[x]
// console.log(new Date(from_date),'latest timestamp')
console.log(series)
console.log("data",all_data)
from_date=all_data[all_data.length-1][0]
// console.log(from_date)
// series.isDirty=false
// series.isDirtyData=false
for (var i = 0; i < all_data.length; i++)
{
series.addPoint({ x: all_data[i][0],y: all_data[i][1],id: i},false,shift);
}
console.log("series object",series)
// chart.redraw();
console.log(" parameter",data)
data['from-date']=from_date
console.log("data",series.data)
// console.log(chart)
setTimeout(requestData(data), 10000);
console.log("out of success")
},
cache:false,
error:function()
{
console.log("err")
}
});
}
}
$.ajax({
url:serverUrl+'/api/fetch_all_servers/',
type:'GET',
success:function(response){
response = $.parseJSON(response)
sd = response.response.all_servers
$('input[name=select_menue]').optionTree(sd)
},
error:function(){
console.log('error')
}
});
$('.param-button').live('click',function(e){
e.stopPropagation()
})
$('param-select').live('hover',function(){
$(this).find('.type-select').show()
});
$('.final_value').live('change',function(){
select_name = 'select_menue_'
param_list = []
var param=$('select[name="'+select_name+'"] option:selected').attr('value')
while(param){
param_list.push(param)
select_name += '_'
var param=$('select[name="'+select_name+'"] option:selected').attr('value')
}
console.log(param_list,"param_list")
from_date=new Date().getTime()-300000 //5 minute data
hostname=param_list[0]
TypeOfParameter= param_list[1]
sub_type_parameter=param_list[param_list.length-1]
data = {'type':TypeOfParameter,'hostname':hostname,'param':sub_type_parameter,'from-date':from_date}
var sub_type;
if(param_list.length==4){
sub_type=param_list[2]
data['sub-type'] = sub_type
}
else
{
sub_type=sub_type_parameter
}
// console.log(hostname,TypeOfParameter,sub_type,sub_type_parameter)
data = {'type':TypeOfParameter,'hostname':hostname,'sub-type':sub_type,'param':sub_type_parameter,'from-date':from_date}
requestData(data)
$('#loadingmessage').show(); // show the loading message.
chart = $('#first').highcharts();
if(TypeOfParameter=='cpu')
{
console.log("adding axis")
chart.addAxis({ // Primary yAxis
id:'Cpu_axis'+sub_type_parameter,
labels: {
formatter: function() {
return this.value;
},
style: {
color: '#89A54E'
}
},
title: {
text: "core "+ sub_type+ " "+sub_type_parameter,
style: {
color: '#89A54E'
}
},
lineWidth: 1,
lineColor: '#08F'
});
console.log("adding series")
chart.addSeries({
id:sub_type+sub_type_parameter,
name: "core "+sub_type+" "+sub_type_parameter,
data :[],
tooltip : {
valueSuffix: ' %'
},
yAxis:'Cpu_axis'+sub_type_parameter
})
console.log("series out")
}
if(TypeOfParameter=='memory')
{
chart.addAxis ({
id:'memory'+sub_type_parameter,
labels:{
formatter: function() {
return this.value +'%';
},
style: {
color: '#89C54F'
}
},
title: {
text:sub_type+" "+sub_type_parameter
},
lineWidth: .5,
lineColor: '#08F',
opposite: true
});
chart.addSeries({
id:sub_type+sub_type_parameter,
name: sub_type+'memory usage',
data: [],
tooltip: {
valueSuffix: '%'
},
yAxis:'memory'+sub_type_parameter
});
}
if(TypeOfParameter=='disk')
{
chart = new Highcharts.Chart({
chart: {
renderTo: 'second',
defaultSeriesType: 'spline',
events: {
load: requestData
}
},
title: {
text: 'disk Usage'
},
xAxis: {
type: 'datetime',
tickPixelInterval: 150,
maxZoom: 20 * 1000
},
yAxis: {
minPadding: 0.2,
maxPadding: 0.2,
title: {
text: 'disk',
margin: 80
}
},
series: [{
id:sub_type+sub_type_parameter,
name: 'disk',
data: []
}]
});
}
if(TypeOfParameter=='db')
{
chart = new Highcharts.Chart({
chart: {
renderTo: 'second',
defaultSeriesType: 'spline',
events: {
load: requestData
}
},
title: {
text: 'mongo Usage'
},
xAxis: {
type: 'datetime',
tickPixelInterval: 150,
maxZoom: 20 * 1000
},
yAxis: {
minPadding: 0.2,
maxPadding: 0.2,
title: {
text: 'mmongo',
margin: 80
}
},
series: [{
id:sub_type+sub_type_parameter,
name: 'mongo',
data: []
}]
});
}
if(TypeOfParameter=='redis')
{
chart = new Highcharts.Chart({
chart: {
renderTo: 'second',
defaultSeriesType: 'spline',
events: {
load: requestData
}
},
title: {
text: 'redis Usage'
},
xAxis: {
type: 'datetime',
tickPixelInterval: 150,
maxZoom: 20 * 1000
},
yAxis: {
minPadding: 0.2,
maxPadding: 0.2,
title: {
text: 'redis',
margin: 80
}
},
series: [{
id:sub_type+sub_type_parameter,
name: 'redis',
data: []
}]
});
}
$('#loadingmessage').hide(); // hide the loading message
}
)
});
i am stuck on this problem for quite a while. and still not able to figure out the solution.
here is the full code link
someone please please help. feeling frustrated ..:-(
As you know the addPoint method is bit dangerous when dealing with quite lots points. It is recommended to disable redraw per point when dealing with many new points - more info http://api.highcharts.com/highcharts#Series.addPoint() , I notice you are doing that already in the loop statement, but why did you commented out? have you tried enabling again. Make sure chart.redraw works by adding a new redraw chart event, and set an alert or console log.
Also you may try using, below as part of ajax, instead of cache:false. I had some problems in past.
headers: { 'Cache-Control': 'no-cache' }
Cheers

Categories

Resources