How do I initialize HighChart series values with AJAX? - javascript

I'm trying to dynamically initialize my HighChart series values before first data point is requested using ajax. I can't seem to figure out what is going wrong or if what I'm trying is even possible. Can someone please take a look and help?
$(document).ready(function() {
chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
defaultSeriesType: 'spline',
marginRight: 10,
events: {
load: requestData
}
},
title: {
text: 'Test'
},
xAxis: {
type: 'datetime',
tickPixelInterval: 100,
},
yAxis: {
title: {
text: 'Test'
},
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);
}
},
series: [{
//AJAX NOT WORKING HERE
name: 'Random data',
data: (function() {
var data = [];
$.ajax({
type: "GET",
url: "/test/random2.php",
data: "p=2",
dataType: "json",
async: false,
success: function(result){
var values = JSON.parse(JSON.stringify(result));
var time = (new Date()).getTime();
for (i = -19; i <= 0; i += 1) {
data.push({
x: time + i * 60000,
y: values[i+19];
});
}
}
});
return data;})
}]
});
});
UPDATED CODE
Here is my working solution
function doHighChart(data) {
chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
type: 'spline',
marginRight: 10,
events: {
load: requestData
}
},
title: {
text: 'Test'
},
xAxis: {
type: 'datetime',
tickPixelInterval: 100,
},
yAxis: {
title: {
text: 'Test'
},
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);
}
},
series: [{
name: 'Random data',
data: data
}]
});
}
$(document).ready(function() {
var data = [];
$.ajax({
type: "GET",
url: "/test/random2.php",
data: "p=2",
dataType: "json",
async: false,
success: function(result){
var values = JSON.parse(JSON.stringify(result));
var time = (new Date()).getTime();
for (i = -19; i <= 0; i += 1) {
//data.push([i, -i]);
//data.push("{x:" + (time + i * 1000) ", y: " + values[i+19] + "}");
data.push([
time + i * 1000,
values[i+19]
]);
}
doHighChart(data);
}
});
});

You need to call $.ajax() and in callback initialise your chart.

Related

Javascript Heavy Scripting Load(Lags the website)

I have the website that runs on javascript 1.7.1 and everytime i click a button that runs the Javascript method, the web load becomes far more heavier and continuously run the javascript up to the point that the site starts to lag.Here is an example of my JS method:
function makeGraph() {
var cityValue = [];
var cityValue2 = [];
var cityName = [];
var numIndex = [];
var tDelivery = [];
var tIdle = [];
var tRepair = [];
var tReady = [];
var barColor = "";
var cityString = "";
var chrt = document.getElementById("myCanvas");
var cityList = [];
cityList = arguments;
$.ajax({
url: '../api/values',
type: 'GET',
datatype: 'json',
success: function (data) {
for (var j = 1; j < cityList.length; j++)
{
cityString = cityString + "||" + " data[i].Names==\"" + cityList[j] + "\"";
}
cityString = "data[i].Names==\"" + cityList[0] + "\""+cityString;
for (var i = 0; i < data.length; i++) {
if (eval(cityString)) {
numIndex.push(i);
}
}
for (var k = 0; k < numIndex.length; k++) {
cityValue.push(data[numIndex[k]].ValuesDouble);
cityValue2.push(data[numIndex[k]].ValuesDouble2);
cityName.push(data[numIndex[k]].Names);
tDelivery.push(data[numIndex[k]].truckDelivery);
tIdle.push(data[numIndex[k]].truckIdle);
tRepair.push(data[numIndex[k]].truckRepair);
tReady.push(data[numIndex[k]].truckReady);
}
if (numIndex.length > 0) {
for (var h = 0; h < numIndex.length - 1; h++) {
barColor = barColor + "{y:" + cityValue2[h] + ",color:'" + setGraphColor(cityValue2[h], cityValue[h]) + "'}" + ",";
}
barColor = "[" + barColor + "{y:" + cityValue2[numIndex.length-1] + ",color:'" + setGraphColor(cityValue2[numIndex.length-1],cityValue[numIndex.length-1]) + "'}" + "]";
}
else {
barColor = "[" + barColor + "{y:" + data[numIndex[0]].ValuesDouble2 + ",color:'" + setGraphColor(data[numIndex[0]].ValuesDouble2, data[numIndex[0]].ValuesDouble) + "'}" + "]";
}
$(function () {
Highcharts.chart('container', {
chart: {
type: 'column',
backgroundColor: 'black'
},
tooltip: {
formatter: function () {
var s = '<b>' + this.x + '</b><br/><div>__________________________</div><hr>';
$.each(this.points, function () {
s += '<br/><span style="color:' + this.series.color + '">\u25CF</span><b>' + this.series.name + '</b>: ' + this.y;
});
return s;
},
shared: true
},
title: {
text: ''
},
xAxis: {
categories: cityName,
},
yAxis: {
min: 0,
tickInterval: 500,
title: {
text: ''
}
},
legend: {
verticalAlign: 'top',
reversed: false,
backgroundColor: 'lightgrey'
},
plotOptions: {
series: {
stacking: 'normal'
}
},
series: [{
name: 'Daily Schedule',
data: eval(barColor)
},
{
name: 'Actual Delivery',
data: cityValue,
color: '#33FF66'
},
{
name: '0%-69%',
//data: cityValue,
color: '#FF3366'
},
{
name: '70%-89%',
// data: cityValue,
color: '#FFCC33'
},
{
name: '90%-100%',
// data: cityValue,
color: '#003DF5'
}]
});
});
//////////////GRAPH 2 INFLUENCE///////////
$(function () {
Highcharts.chart('container2', {
chart: {
type: 'column',
backgroundColor: 'black'
},
tooltip: {
formatter: function () {
var s = '<b>' + this.x + '</b><br/><div>__________________________</div><hr>';
$.each(this.points, function () {
s += '<br/><span style="color:' + this.series.color + '">\u25CF</span><b>' + this.series.name + '</b>: ' + this.y;
});
return s;
},
shared: true
},
title: {
text: ''
},
xAxis: {
categories: cityName,
},
yAxis: {
min: 0,
max:80,
tickInterval: 20,
title: {
text: ''
}
},
legend: {
verticalAlign: 'top',
reversed: false,
backgroundColor: 'lightgrey'
},
plotOptions: {
series: {
stacking: 'normal'
}
},
series: [
{
name: 'Truck Delivery',
data: tDelivery,
color: '#33FF66'
},
{
name: 'Truck Idle',
data: tIdle,
color: '#FFCC33'
},
{
name: 'Truck Repair',
data: tRepair,
color: '#FF3366'
},
{
name: 'Truck Ready',
data: tReady,
color: '#003DF5'
}]
});
});
//////////////GRAPH 3 INFLUENCE///////////
$(function () {
Highcharts.chart('container3', {
chart: {
type: 'column',
backgroundColor: 'black'
},
tooltip: {
formatter: function () {
var s = '<b>' + this.x + '</b><br/><div>__________________________</div><hr>';
$.each(this.points, function () {
s += '<br/><span style="color:' + this.series.color + '">\u25CF</span><b>' + this.series.name + '</b>: ' + this.y;
});
return s;
},
shared: true
},
title: {
text: ''
},
xAxis: {
categories: cityName,
},
yAxis: {
min: 0,
tickInterval: 500,
title: {
text: ''
}
},
legend: {
verticalAlign: 'top',
reversed: false,
backgroundColor: 'lightgrey'
},
plotOptions: {
series: {
stacking: 'normal'
}
},
series: [
{
name: 'Staff On Duty',
data: cityValue,
color: '#33FF66'
},
{
name: 'Staff Present',
data: cityValue,
color: '#003DF5'
},
{
name: 'Staff Absent',
data: cityValue,
color: '#FF3366'
}]
});
});
}
})
}
I also have run a developer tool in IE 11 which shows me that it is indeed from the nonstop javascript loop. I was wondering if anyone could help me stop the JS loop so that it is not continuous.(I am also using SignalR and i dont know if this is one of the factors).Thanks in advance.
These are the header tags:
<meta name="viewport" content="width=device-width" />
<script src="Scripts/jquery-1.7.1.min.js"></script>
<script src="Scripts/jquery.signalR-2.2.1.min.js"></script>
<script src="Scripts/highcharts/4.2.0/highcharts.js"></script>
<script src="Scripts/Chart.min.js"></script>
<script src="Scripts/Chart.js"></script>
<script src="/signalr/hubs" type="text/javascript"></script>
<script type="text/javascript">
and yes, I am using highchart.js in this function and the button is that so i can refresh and sort the graph according to the buttons i clicked which in these cases are categories of cities.

How to stop ticks to moveout of axis in Highcharts

I have a similar requirement and created a fiddle
I am trying to make use of tickPositions to set the xAxis ticks but the problem is the ticks are moving out of the chart window. Can, any one please help me with this. Also, please let me know if I am doing something wrong.
$(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];
var xAxis = this.xAxis[0];
setInterval(function() {
var x = (new Date()).getTime(), // current time
y = Math.random();
series.addPoint([x, y], true, true);
xAxis.options.tickPositions.push(x);
}, 1000);
}
}
},
title: {
text: 'Live random data'
},
xAxis: {
type: 'datetime',
tickPositions: [],
labels: {
formatter: function() {
return Highcharts.dateFormat('%H:%M:%S', this.value);
}
},
},
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 = -10; i <= 0; i += 1) {
data.push({
x: time + i * 1000,
y: Math.random()
});
}
return data;
}())
}]
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<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: 310px; height: 400px; margin: 0 auto"></div>

highstock 2.0.4 not working on IE and Firefox

I have the data as below:
{"01.12.10 00:00":-1.5821800231934,"01.12.10 00:05":-1.5570800304413,"01.12.10 00:10":-1.5885699987411,"01.12.10 00:15":-1.6257599592209,"01.12.10 00:20":-1.6307400465012,"01.12.10 00:25":-1.6432000398636,"01.12.10 00:30":-1.655179977417,"01.12.10 00:35":-1.646919965744,"01.12.10 00:40":-1.6347700357437,"01.12.10 00:45":-1.6490000486374,"01.12.10 00:50":-1.6404999494553,"01.12.10 00:55":-1.6160600185394,"01.12.10 01:00":-1.6089400053024,"01.12.10 01:05":-1.6082600355148,"01.12.10 01:10":-1.6159199476242,"01.12.10 01:15":-1.5781999826431,"01.12.10 01:20":-1.6013100147247,"01.12.10 01:25":-1.636440038681,"01.12.10 01:30":-1.6679799556732,"01.12.10 01:35":-1.6709300279617,"01.12.10 01:40":-1.7158499956131,"01.12.10 01:45":-1.7515499591827,"01.12.10 01:50":-1.7836400270462,"01.12.10 01:55":-1.7883299589157,"01.12.10 02:00":-1.8029299974442,"01.12.10 02:05":-1.8306200504303,"01.12.10 02:10":-1.8690099716187,"01.12.10 02:15":-1.8802800178528,"01.12.10 02:20":-1.890319943428,"01.12.10 02:25":-1.9045300483704,"01.12.10 02:30":-1.9173899888992,"01.12.10 02:35":-1.9262299537659,"01.12.10 02:40":-1.9494600296021,"01.12.10 02:45":-1.9754300117493,"01.12.10 02:50":-2.0177900791168,"01.12.10 02:55":-2.1353900432587,"01.12.10 03:00":-2.2930901050568,"01.12.10 03:05":-2.4463000297546,"01.12.10 03:10":-2.4375700950623,"01.12.10 03:15":-2.4210600852966,"01.12.10 03:20":-2.4662098884583}
And my script to initialize the graph is as follows:
getGraphData: function(params){
var self = this;
$.ajax({
url: '_someUrl' + params,
type: 'GET',
success:function(result){
self.renderBarChart(self.formatData(result));
},
error: function(req, status, error){
console.log(error);
}
});
},
formatData: function(rawData){
var self = this;
var result = $.parseJSON(rawData);
var formattedData = _.map(result, function(value, date){
var formattedDate =self.formatDate(date);
return [formattedDate, value];;
});
return formattedData;
},
formatDate: function(rawDate){
var dateTimeArray = rawDate.split(' ');
var dateArray = dateTimeArray[0].split('.');
var newDateTimeString = (dateArray[1] + '.' + dateArray[0] + '.' + dateArray[2] + ' ' + dateTimeArray[1]);
return new Date(newDateTimeString).getTime();
},
renderBarChart: function(data){
Highcharts.setOptions({
lang: {
rangeSelectorFrom: 'Von',
rangeSelectorTo: 'Bis'
}
});
$('#container').highcharts('StockChart', {
chart: {
alignTicks: false,
type: 'column'
},
xAxis: {
type: 'datetime',
title: {
text: 'Date'
},
labels: {
formatter: function() {
return Highcharts.dateFormat(" %e %b %Y %H:%M:%S", this.value);
},
rotation: 90
},
tickLength: 0
},
rangeSelector: {
selected: 1,
allButtonsEnabled: true,
enabled: true
},
series: [{
name: 'Datai',
data:data,
tooltip: {
formatter: function() {
var tooltip = '<b>Datum</b>: ' + Highcharts.dateFormat("%e %b %Y %H:%M:%S", this.x) + '</b><br>';
tooltip += '<b>Werte: </b>' + this.y;
return tooltip;
}
}
}]
}, function(chart) {
setTimeout(function() {
$('input.highcharts-range-selector', $('#' + chart.options.chart.renderTo)).datepicker()
}, 0)
});
}
It works fine with chrome but shows the following error on any versions of IE and also on Firefox.
TypeError: segmentPositions is undefined highstock.src.js:17778
TypeError: series[j].tooltipPoints is undefined highstock.src.js:9113
I think the problem is with the data grouping but since I don't neeed to group the data, so I tried various options but could not make it work. Any help yould be greatly appriciated.
Your json is incorrect, the point should have x/y fields, x should be timestamp (time in miliseconds) not as you have.

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 ?

Unable to plot data json data on highcharts

I am trying to load json data to high-charts. I am receiving json data from DB using $.getJSON function. Here is my sample json that i am receiving from DB,
My sample json
[
{
"target":"collectd.matrix.oracle.avg_resp_time","datapoints":[[8.0, 1365158480],[null, 1365158490],[null, 1365158500],[null, 1365158510],[null, 1365158520],[null,1365158530],[8.0, 1365158540],[null, 1365158550],[null, 1365158560],[null, 1365158570],[null, 1365158580],[null, 1365158590]]
}
]
$.getJSON("myURL", createOrderDurationChart);
On success response from $.getJSON i call function below,
I am using scala framework.
I am not getting what is wrong in code or json. I can plot this json by embedding code in simple javascript and run through html directly as sample.
Here is the sample code,
function createOrderDurationChart(durationMap){
//var target=durationMap[0].target;
//var jsonstr=durationMap[0].datapoints;
//alert(target);
//alert(jsonstr);
var orderDurationChart = new Highcharts.Chart({
chart: {
renderTo: "order_duration_div",
type: "column",
margin: [10, null, null, null],
//marginRight: 10,
zoomType: 'xy',
},
title: {
text: "order duration"
//y: 5
},
xAxis: {
type: "datetime",
//tickInterval: 60*1000*10
},
yAxis: {
title: {
text: "seconds"
},
startOnTick : false,
endOnTick: false
},
series: [{
name:"avg",
data: (function (){
var data = [], i;
var jsondata = [];
jsondata= durationMap[0].datapoints;
alert(jsondata)
var datapoints=JSON.parse(jsondata);
// var jsonstr=parsejson[0].datapoints;
console.log('jsotn ' + datapoints);
// var mydata = JSON.parse(jsonstr);
// alert(mydata);
// datapoints = mydata[0].datapoints;
//alert("initial:" + json[0].time + ':' + json[0].value);
for (i = 0; i < datapoints.length; i++) {
data.push({
x:datapoints[i][1],
y:datapoints[i][0]
});
console.log('x: ' + datapoints[i][1] + ', y: ' + datapoints[i][0]);
}
return data;
})
()}]
});
}
Update code after json fix,
function createOrderDurationChart(durationMap){
//var target=durationMap[0].target;
//var jsonstr=durationMap[0].datapoints;
//alert(target);
//alert(jsonstr);
var orderDurationChart = new Highcharts.Chart({
chart: {
renderTo: "order_duration_div",
type: "column",
margin: [10, null, null, null],
//marginRight: 10,
zoomType: 'xy',
},
title: {
text: "order duration"
//y: 5
},
xAxis: {
type: "datetime",
//tickInterval: 60*1000*10
},
yAxis: {
title: {
text: "seconds"
},
startOnTick : false,
endOnTick: false
},
series: [{
name:"avg",
data: (function (){
var data = [], i;
var jsondata = [];
datapoints= durationMap[0].datapoints;
console.log('jsotn ' + datapoints);
for (i = 0; i < datapoints.length; i++) {
data.push({
x:datapoints[i][1],
y:datapoints[i][0]
});
console.log('x: ' + datapoints[i][1] + ', y: ' + datapoints[i][0]);
}
return data;
})
()}]
});
}
Any suggestions most welcome.
Thanks

Categories

Resources