Ajax dynamic data with column bar chart - javascript

Is it possible to run the highcharts column bar charts? I've tried it a couple of times and unfortunately this no real way to refresh the data without reloading it.
I whipped up some pseudo code which is the way I did it at work (I'm not there now so can't get to the code).
Should I whip up a loop and run it like 5,000 times or something with a 5 second delay? I'm not real sure how to proceed.
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Highcharts Example</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script type="text/javascript">
< your typical ajax call function here
return some value;
>
$(function () {
<var ajax_far = ajax_function();>
var chart;
$(document).ready(function() {
chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
type: 'column'
},
title: {
text: 'Monthly Average Rainfall'
},
subtitle: {
text: 'Source: WorldClimate.com'
},
xAxis: {
categories: [
'Some Bar'
]
},
yAxis: {
min: 0,
title: {
text: 'Rainfall (mm)'
}
},
legend: {
layout: 'vertical',
backgroundColor: '#FFFFFF',
align: 'left',
verticalAlign: 'top',
x: 100,
y: 70,
floating: true,
shadow: true
},
tooltip: {
formatter: function() {
return ''+
this.x +': '+ this.y +' mm';
}
},
plotOptions: {
column: {
pointPadding: 0.2,
borderWidth: 0
}
},
series: [{
name: 'Tokyo',
data: [ajax_var]
}]
});
});
}, 5000);
</script>
</head>
<body>
<script src="http://code.highcharts.com/highcharts.js"></script>
<script src="http://code.highcharts.com/modules/exporting.js"></script>
<div id="container" style="min-width: 400px; height: 400px; margin: 0 auto"></div>
</body>
</html>

put your ajax code in one function that it call from ready function...try this
$(document).ready(function(){
example();
setInterval("example()",5000);
}
function example()
{
//ajax code here
}

The ajax call should simply obtain new data for the chart to display. There is no need to redraw the entire chart, you can just replace the series data, or add indivual points. Here is a good article on doing this on the highcharts website here http://docs.highcharts.com/#preprocessing-live-data, but the ajax code they suggest is:
/**
* 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 2.
// Add the point.
chart.series[0].addPoint(point, true, shift);
// Call it again after one second.
setTimeout(requestData, 1000);
},
cache: false
});
}
In this code, the requestData function is called every second (via setTimout). It obtains a new data point via an ajax call to live-server-data.php and uses chart.series[0].addPoint to add it to the chart.
If the ajax call returned the entire series, you would call chart.series[0].setData to replace the entiire series.
The only thing you need to worry about is making sure the chart is created before you start call addPoint or setData.

$(function () {
var chart;
var list;
$(document).ready(function() {
var options = {
chart: {
//all chart attr here
}
//other attr
}
chart = new Highcharts.Chart(options);
setInterval(function() {
$.ajax({
type: "GET",
url: "service",
dataType: "json",
success: function (data)
{
chart.series[0].setData(data);
}
}),1000); //will set ur data to ajax data every 1 sec
if u want to update to existing chart data try addPoint()
});
});

Related

HighChart- Wrong Datetime in the X-Axis for Live Chart

I am using HighChart for Live Chart (Data changes each 10 seconds).In each Second , an ajax call will take place and get the data from the Controller as json. In the example , I can get the data in each 10 seconds but the time shows in the X-axis is wrong. Instead of showing the correct time , it showing the time more than 4 from the current time.
This is the HTML+js file
<!DOCTYPE html>
<html>
<head>
<title>Index</title>
#*//Add JQUERY*#
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.1.1.min.js"></script>
#*//Add HighChart.js*#
<script src="http://code.highcharts.com/highcharts.js"></script>
<script>
var chart;
$(document).ready(function () {
chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
defaultSeriesType: 'spline',
events: {
load: getData
}
},
title: {
text: 'Live Bin Usage'
},
xAxis: {
type:'datetime',
tickPixelInterval: 150
},
yAxis: {
minPadding: 0.2,
maxPadding: 0.2,
title: {
text: 'Value',
margin: 80
}
},
series: [{
name: 'Time'
}]
});
});
/**
* Request data from the server, add it to the graph and set a timeout to request again
*/
function getData() {
$.ajax({
url: '/AswinDemo/FetchData',
dataType: 'json',
success: function (data) {
var series = chart.series[0],
shift = series.data.length > 20; // shift if the series is
// longer than 20
var x = (new Date()).getTime(), // current time
y = Math.random();
// add the point
chart.series[0].addPoint([x ,data.BinUsage], true, shift);
// call it again after one second
setTimeout(getData, 1000);
},
cache: false
});
}
</script>
</head>
<body>
<div id="container" style="width:100%; height:400px;"></div>
</body>
</html>
The server or Controller
public ActionResult FetchData()
{
Random rn = new Random();
return Json(new { BinUsage = rn.Next(), Time = DateTime.Now.TimeOfDay.ToString()} ,JsonRequestBehavior.AllowGet );
}
Below is the Screen Shot of the Chart : -
You can see the time in my chart is deffer from the time of the PC (in the task bar)
I have solved the problem by setting global.useUTC to false. Thanks.

Highchart column animation when adding new column

I'm trying to make a simple bar chart that updates every 5 seconds using highchart. Below is my code:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://code.highcharts.com/highcharts.js"></script>
<script src="https://code.highcharts.com/modules/exporting.js"></script>
<script src="underscore-min.js"></script>
</head>
<body>
<div id="container" style="min-width: 310px; height: 400px; margin: 0 auto"></div>
</body>
<script>
Highcharts.chart('container', {
chart: {
type: 'column'
},
title: {
text: 'Activity Count per Model'
},
xAxis: {
categories: [],
crosshair: true,
title: {
text: 'Model'
}
},
yAxis: {
min: 0,
title: {
text: 'Activity Count'
}
},
plotOptions: {
column: {
animation: true,
pointPadding: 0.2,
borderWidth: 0
}
},
series: [{
name: 'Count',
data: []
}]
});
setInterval(function(){
$.getJSON("http://localhost/getdata.php", function(data){
$('#container').highcharts().series[0].setData(data.value,true);
$('#container').highcharts().xAxis[0].setCategories(data.model);
});
}, 5000);
</script>
</html>
The data returned from JSON call:
{"model":["a","aa","aaa","aaaa","aab","b","c","d","e"],"value":[40,20,70,40,70,20,30,40,50]}
Right now functionally the code works fine (chart shows up with the data updated every 5 second). The problem is that if the chart updates with new column, there's no animation on it. But if the existing data is updated without adding new column, there's animation in it (column growing up / shrinking, other column adjust if axis change). How do I enable the animation when new column is inserted into the chart?
In that case there are different possibilities how the chart should be animated. So you should consider what animation you'd want to.
From setData() docs:
When the updated data is the same length as the existing data, points will be updated by default, and animation visualizes how the points are changed.
IN your case you can split your data in two parts - the new point and the rest data. The rest data can be set with setData() - and you will preserve the animation because the old and new data have same length. And the point can be added with animation via addPoint().
$('#button').click(function () {
const data = new Array(12).fill(2)
chart.xAxis[0].setCategories(categories.concat('13'), false);
chart.series[0].setData(data);
chart.series[0].addPoint(40, true, false, true);
});
example: http://jsfiddle.net/Lqy2e42h/

Golang Highcharts dynamic data

I am currently learning golang and a bit of webstuff on the way. So excuse my maybe not so smart question
My problem is that I want to provide a Highchart with dynamic Data. I looked up the documentation and the example but cannot get it to work.
The Highchart example:
<script type="text/javascript" src="http://code.jquery.com/jquery-1.10.1.js"></script>
<script type="text/javascript" src="http://code.highcharts.com/highcharts.js"></script>
<!-- 2. Add the JavaScript to initialize the chart on document ready -->
<script>
var chart; // global
/**
* Request data from the server, add it to the graph and set a timeout to request again
*/
function requestData() {
$.ajax({
url: 'http://localhost:3000/',
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(eval(point), true, shift);
// call it again after one second
setTimeout(requestData, 1000);
},
cache: false
});
}
$(document).ready(function() {
chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
defaultSeriesType: '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: [1]
}]
});
});
</script>
</head>
<body>
<!-- 3. Add the container -->
<div id="container" style="width: 800px; height: 400px; margin: 0 auto"></div>
My Server should Provide a json encoding string as requested.
func main(){
http.HandleFunc("/",foo)
http.ListenAndServe(":3000", nil)
}
func foo(w http.ResponseWriter, r *http.Request) {
numbers := []int{14,5}
js, err := json.Marshal(numbers)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
fmt.Println("Received Request")
w.Header().Set("Content-Type", "text/json")
w.Write(js)
}
I can see that the highchart makes a request. My guess it that the ajax call does not understand my json?
Thanks for any help in advance :)
Edit: Do I habe to do a success message as a return too?
The error (thx to #jmaloney 's hint)
{"readyState":4,"status":200,"statusText":"success"}
ajax.html:28 parsererror: Error: jQuery110109016359453089535_1446814074235 was not called
A simple
w.Header().Set("Access-Control-Allow-Origin", "*")
on my go-Server solves it :)

HighCharts with Dynamic Data not working

I have a ASP.NET MVC project with SignalR.
I have a page with a HighChart and the script looks like this:
$(function () {
window.Highcharts.setOptions({
global: {
useUTC: false
}
});
var chart;
$(document).ready(function () {
chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
type: 'line',
marginRight: 10
},
title: {
text: 'GMAS Queues'
},
xAxis: {
type: 'datetime',
tickInterval: 500,
labels: {
enabled: false
}
},
yAxis: {
title: {
text: 'Queue Count'
},
plotLines: [{
value: 0,
width: 1,
color: '#808080'
}]
},
legend: {
enabled: false
},
exporting: {
enabled: false
},
series: [{
name: 'Processing Queues'
}]
});
});
$.connection.hub.logging = true;
// Reference the auto-generated proxy for the hub.
var chartData = $.connection.processingQueuesHub;
// Create a function that the hub can call back to display messages.
chartData.client.updateQueueCounts = function (data) {
//$.each(data, function(i, item) {
// // Add the message to the page.
// $('#chartDataLog').append('<li><strong>' + htmlEncode(item.QueueName)
// + '</strong>: ' + htmlEncode(item.Length) + '</li>');
//});
// set up the updating of the chart.
var series = chart.series[0];
$.each(data, function (i, item) {
if (item.QueueName == "Queue A") {
var x = Date.parse(item.Date),
y = item.Length;
series.addPoint([x, y], true, false);
}
});
};
However, I see the graph but not the points.
The strange part is the series data points are there:
Anyone know why HighCharts is not rendering the points?
Thanks, Bill N
I have to thank my good friend and co developer for figuring this out. He is a smarter and braver man than me. :) He went to the highcharts source and found that the highcharts breaks if you add to the graph series before the initial animation is completed. The animation is why the clip-rect is zero-width (it animates from zero to full width over 1s when you first create the chart). You end up adding a point to the series before this animation even really starts. This kills the animation but it doesn’t fix the width of the clip-rect. The fix is to add animation is false for the series.
series: [{ name: 'Processing Queues', data: [], animation: false }]
It looks like you are not defining what your chart.series is until it is created. The line in your ajax is as follows and its not waiting for DOM ready:
var series = chart.series[0];
But you do not define chart until $(document).ready(function () {.... Try keeping your chart object in scope of your ajax.

Highcharts multiple charts, each with live data

I have the following files:
rsrp.txt, sinr.txt, rssi.txt
each of them containg information like this:
[1433289760000,-83.5]
I want to use multiple charts on the same page.
I tried to use the sample script from the Highcharts page:
var chart; // global
/**
* Request data from the server, add it to the graph and set a timeout to request again
*/
function requestData() {
$.ajax({
url: 'rssi.txt',
success: function(point) {
var series = chart.series[0],
shift = series.data.length > 30; // shift if the series is longer than 20
// add the point
chart.series[0].addPoint(eval(point), true, shift);
// call it again after one second
setTimeout(requestData, 1700);
},
cache: false
});
}
$(document).ready(function() {
chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
defaultSeriesType: 'spline',
events: {
load: requestData
}
},
title: {
text: 'RSSI'
},
xAxis: {
type: 'datetime',
tickPixelInterval: 150,
maxZoom: 20 * 1000
},
yAxis: {
minPadding: 2.5,
maxPadding: 2.5,
title: {
text: 'dBm',
margin: 80
}
},
series: [{
name: 'RSSI',
data: []
}]
});
});
Copy pasting the script outside the and changing the URL does not work. (only one chart is getting updates)
If I create a second requestData()-function and copy the $(document).ready part does not work either.
Is this possible in Highcharts?
It would be not a problem to combine the input files into a single file, if that would help.
Edit:
I tried to solve it using the answers here:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Signal</title>
<!-- 1. Add these JavaScript inclusions in the head of your page -->
<script type="text/javascript" src="jquery-1.10.1.js"></script>
<script type="text/javascript" src="highcharts.js"></script>
<!-- 2. Add the JavaScript to initialize the chart on document ready -->
<script>
var chart; // global
var chartRsrp;
/**
* Request data from the server, add it to the graph and set a timeout to request again
*/
function requestData() {
$.ajax({
url: 'rssi.txt',
success: function(point) {
var series = chart.series[0],
shift = series.data.length > 30; // shift if the series is longer than 20
// add the point
chart.series[0].addPoint(eval(point), true, shift);
// call it again after one second
setTimeout(requestData, 1700);
},
cache: false
});
}
function requestData2() {
$.ajax({
url: 'rsrp.txt',
success: function(point) {
var series = chartRsrp.series[0],
shift = series.data.length > 30; // shift if the series is longer than 20
// add the point
chartRsrp.series[0].addPoint(eval(point), true, shift);
// call it again after one second
setTimeout(requestData, 1700);
},
cache: false
});
}
$(document).ready(function() {
chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
defaultSeriesType: 'spline',
events: {
load: requestData
}
},
title: {
text: 'RSSI'
},
xAxis: {
type: 'datetime',
tickPixelInterval: 150,
maxZoom: 20 * 1000
},
yAxis: {
minPadding: 2.5,
maxPadding: 2.5,
title: {
text: 'dBm',
margin: 80
}
},
series: [{
name: 'RSSI',
data: []
}]
});
chartRsrp = new Highcharts.Chart({
chart: {
renderTo: 'container2',
defaultSeriesType: 'spline',
events: {
load: requestData2
}
},
title: {
text: 'RSRP'
},
xAxis: {
type: 'datetime',
tickPixelInterval: 150,
maxZoom: 20 * 1000
},
yAxis: {
minPadding: 2.5,
maxPadding: 2.5,
title: {
text: 'dBm',
margin: 80
}
},
series: [{
name: 'RSRP',
data: []
}]
});
});
</script>
</head>
<body>
<!-- 3. Add the container -->
<div id="container" style="width: 800px; height: 400px; margin: 0 auto"></div>
<div id="container2" style="width: 800px; height: 400px; margin: 0 auto"></div>
Edit 2: solved it that way:
requestData2();
requestData3();
requestData4();
setTimeout(requestData, 1300);
in the first requestData()
In Highcharts-land, each chart needs to be its own object. It's certainly possible to have multiple charts on the same page, but you'd have to make sure that:
Each chart is instantiated separately (in this case, if you're just copying/pasting the $(document).ready part, you're probably stepping on your chart variable. So, instead of a single chart variable you could set these up separately (e.g. chartRsrp = new Highcharts.Chart(...)) and be sure to reference them differently in your requestData calls.
Each chart is rendered to a different DOM element. So, you might render to "container-rsrp", "container-sinr", "container-rssi" etc.
Hopefully this helps!
First of all, each chart have to be instantiated separately, so in your HTML you must have a div with an ID for each chart where the chart will be rendered, for example:
<div id='chartrsrp' class="large-12 columns"></div>
<div id='chartsinr' class="large-12 columns"></div>
<div id='chartrssi' class="large-12 columns"></div>
Next, to render your chart from Js you have to get the div object and instantiate each chart like:
var chartrsrp = $("#chartrsrp");
chartrsrp.highcharts({
title: {
...
},
chart: {
...
});
Hopefully this helps!

Categories

Resources