Highcharts load data from server ok, but not updating - javascript

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]]

Related

Display 100 Points in 1 second : Highcharts

So I have a project where I am trying to update chart. in which 100 points to be displayed in each second.
For that I am trying this example from the Highcharts.
But the chart stops responding to such event.
The code:
jsfiddle
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);
}, 10);
}
}
},
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: Math.random()
});
}
return data;
}())
}]
});
You can set redraw parameter in addPoint method to false and call chart.redraw() at longer intervals:
chart: {
...,
events: {
load: function() {
// set up the updating of the chart each second
var series = this.series[0],
chart = this;
setInterval(function() {
var x = (new Date()).getTime(), // current time
y = Math.random();
series.addPoint([x, y], false, true);
}, 10);
setInterval(function() {
chart.redraw();
}, 500);
}
}
}
Live demo: https://jsfiddle.net/BlackLabel/s3gh6q5j/
API Reference:
https://api.highcharts.com/class-reference/Highcharts.Series#addPoint
https://api.highcharts.com/class-reference/Highcharts.Chart#redraw

csv live data highchart

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

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.

Live multiple series with highchart

I am trying to display 10 series simultaneously on highcharts. With the following code.
function requestData() {
$.ajax({
url: 'Default3.aspx',
dataType: 'json',
error: function (point) {
var series = chart.series[10],
shift = series.data.length > 50; // shift if the series is longer than 20
chart.series[0].addPoint([0, 1], true, true);
chart.series[1].addPoint([0, 2], true, true);
chart.series[2].addPoint([0, 3], true, true);
chart.series[3].addPoint([0, 4], true, true);
chart.series[4].addPoint([0, 5], true, true);
chart.series[5].addPoint([0, 6], true, true);
chart.series[6].addPoint([0, 7], true, true);
chart.series[7].addPoint([0, 8], true, true);
chart.series[8].addPoint([0, 9], true, true);
chart.series[9].addPoint([0, 10], true, true);
// call it again after one second
setTimeout(requestData, 5000);
},
success: function (point) {
var series = chart.series[10],
shift = series.data.length > 50; // shift if the series is longer than 20
// add the point
// chart.series[0].addPoint(eval(point), true, shift);
chart.series[0].addPoint([0, 1], true, true);
chart.series[1].addPoint([0, 2], true, true);
chart.series[2].addPoint([0, 3], true, true);
chart.series[3].addPoint([0, 4], true, true);
chart.series[4].addPoint([0, 5], true, true);
chart.series[5].addPoint([0, 6], true, true);
chart.series[6].addPoint([0, 7], true, true);
chart.series[7].addPoint([0, 8], true, true);
chart.series[8].addPoint([0, 9], true, true);
chart.series[9].addPoint([0, 10], true, true);
// call it again after one second
setTimeout(requestData, 5000);
},
cache: false
});
}
$(document).ready(function () {
chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
defaultSeriesType: 'line',
events: {
load: requestData
}
},
title: {
text: 'Sensor Data Vs. Time'
},
xAxis: {
type: 'datetime',
tickPixelInterval: 150,
maxZoom: 20 * 1000
},
yAxis: {
minPadding: 0.2,
maxPadding: 0.2,
title: {
text: 'Value',
margin: 80
}
},
series: [{
data: []
},{
data: []
}, {
data: []
}, {
data: []
}, {
data: []
}, {
data: []
}, {
data: []
}, {
data: []
}, {
data: []
}, {
data: []
}]
});
});
Legends of the series is coming on the chart but it is not displaying the data.
I advice replace this:
chart.series[0].addPoint([0, 1], true, true);
//other points as first
chart.series[9].addPoint([0, 10], true, true);
with
chart.series[0].addPoint([0, 1], false, true);
//other points as first
chart.series[9].addPoint([0, 10], true, true);
Points cannot be added to the empty chart, dynamically, but you can set null value on data like here http://jsfiddle.net/g2tka/1/ or use addSeries.
I did some modification on trial and error basis and got it working, Actually i have to use eval function which I was not using previously.
Here is the answer
JavaScript
function requestData() {
$.ajax({
url: 'Default3.aspx',
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);
chart.series[2].addPoint([values[0], values[3]], true, shift);
chart.series[3].addPoint([values[0], values[4]], true, shift);
chart.series[4].addPoint([values[0], values[5]], true, shift);
chart.series[5].addPoint([values[0], values[6]], true, shift);
chart.series[6].addPoint([values[0], values[7]], true, shift);
chart.series[7].addPoint([values[0], values[8]], true, shift);
chart.series[8].addPoint([values[0], values[9]], true, shift);
chart.series[9].addPoint([values[0], values[10]], true, shift);
// call it again after defined seconds
setTimeout(requestData, 5000);
},
success: function (point) {
var series = chart.series[0],
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);
chart.series[2].addPoint([values[0], values[3]], true, shift);
chart.series[3].addPoint([values[0], values[4]], true, shift);
chart.series[4].addPoint([values[0], values[5]], true, shift);
chart.series[5].addPoint([values[0], values[6]], true, shift);
chart.series[6].addPoint([values[0], values[7]], true, shift);
chart.series[7].addPoint([values[0], values[8]], true, shift);
chart.series[8].addPoint([values[0], values[9]], true, shift);
chart.series[9].addPoint([values[0], values[10]], true, shift);
// call it again after defined seconds
setTimeout(requestData, 5000);
},
cache: false
});
}
$(document).ready(function () {
chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
defaultSeriesType: 'spline',
events: {
load: requestData
}
},
title: {
text: 'Sensor Data Vs. Time'
},
xAxis: {
type: 'datetime',
tickPixelInterval: 150,
maxZoom: 20 * 1000
},
yAxis: {
minPadding: 0.2,
maxPadding: 0.2,
title: {
text: 'Value',
margin: 80
}
},
series: [{
name: 'Pressure 1 (PSI)',
data: []
}, {
name: 'Flow 1 (GPM)',
data: []
}, {
name:'Temperature 1 (C)',
data: []
}, {
name: 'Speed 1 (RPM)',
data: []
}, {
name: 'Power 1 (kW)',
data: []
}, {
name:'Pressure 2 (PSI)',
data: []
}, {
name:'Flow 2 (GPM)',
data: []
}, {
name:'Temperature 2 (C)',
data: []
}, {
name: 'Speed 2 (RPM)',
data: []
}, {
name: 'Power 2 (kW)',
data: []
}]
});
});
Server Side Code (C#)
public partial class Default3 : System.Web.UI.Page
{
public DataTable dt = new DataTable();
public string DATA;
List<string> hidXCategories11 = new List<string>();
public string chartData
{
get;
set;
}
protected void Page_Load(object sender, EventArgs e)
{
GetData();
var epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
var timeDiff = DateTime.Now - new DateTime(1970, 1, 1);
var totaltime = timeDiff.TotalMilliseconds;
List<double> _data = new List<double>();
foreach (DataRow row in dt.Rows)
{
_data.Add(totaltime);
_data.Add((double)Convert.ToDouble(row["S11"]));
_data.Add((double)Convert.ToDouble(row["S12"]));
_data.Add((double)Convert.ToDouble(row["S13"]));
_data.Add((double)Convert.ToDouble(row["S14"]));
_data.Add((double)Convert.ToDouble(row["S15"]));
_data.Add((double)Convert.ToDouble(row["S21"]));
_data.Add((double)Convert.ToDouble(row["S22"]));
_data.Add((double)Convert.ToDouble(row["S23"]));
_data.Add((double)Convert.ToDouble(row["S24"]));
_data.Add((double)Convert.ToDouble(row["S25"]));
}
JavaScriptSerializer jss = new JavaScriptSerializer();
chartData = jss.Serialize(_data);
Response.Write(chartData);
}
private void GetData()
{
StringBuilder str = new StringBuilder();
SqlConnection con = new SqlConnection("Data Source=localhost\\SQLEXPRESS;Initial Catalog=MyData;Integrated Security=SSPI");
SqlDataAdapter adp = new SqlDataAdapter("select top 1 * from MyTable order by Id desc ", con);
adp.Fill(dt);
}
}
HTML (.aspx) Code
<script src="JavaScript/highcharts.js"></script>
<script src="JavaScript/exporting.js"></script>
<div id="container" style="min-width: 280px; height: 400px; margin: 0 auto"></div>

Redraw JQplot bar chart with new data and tick labels

My code successfully draws a chart with data and tick labels retrieved as JSON object from PHP. Now at one point i want to refresh the chart but with slightly different data and different tick labels without creating a new chart.
$.jqplot.config.enablePlugins = true;
var freqs1 = [];
var freqlabels1 = [];
var dataRendered1 = $.ajax({
async: false,
url: 'MY_URL',
dataType: 'json',
success: function(data) {
if (data.length) {
freqs1 = data[0];
freqlabels1 = data[1];
}
}
});
var plot1 = $.jqplot('chartdiv', [freqs1], {
animate: !$.jqplot.use_excanvas,
seriesDefaults:{
renderer:$.jqplot.BarRenderer,
pointLabels: {
show: true
},
rendererOptions: {
barWidth: 12
}
},
title:'Test',
axes: {
xaxis: {
renderer: $.jqplot.CategoryAxisRenderer,
ticks: freqlabels1,
label: "Test 1",
tickOptions:{textColor : 'rgb(39, 125, 175)', fontSize: '9pt'}
},
yaxis: {
label: "Test 2",
labelRenderer: $.jqplot.CanvasAxisLabelRenderer,
tickOptions:{textColor : 'rgb(39, 125, 175)', fontSize: '9pt'}
}
},
highlighter: { show: true }
});
now when button is clicked lets say I have an ajax call that gets the new data and tick labels
$(document).on('click', '#refresh_new', function() {
$.ajax({
async: false,
url: 'MY_URL',
dataType: 'json',
success: function(data) {
var newData = data[0];
var newTicks = data[1];
//HOW DO I REFRESH CHART WITH NEW DATA AND TICKS FOR x-AXIS
}
});
});

Categories

Resources