knockout bindings not being applied in rails 3 remote partial load - javascript

I have this view model in a js file that loads with my app:
var portfolioViewModel = function() {
var self = this;
this.selectedCompany = ko.observable('All Companies');
this.allComp = ko.observable(true);
this.chartSeries = ko.observableArray();
$(function(){
self.chart.addSeries(companyChart['All Companies']);
});
$.each(companyData, function(index, company) {
self[company] = ko.observable(false);
self.chartSeries.push(companyChart[company]);
});
this.chart = ko.observable();
this.showCompany = function(company){
self.hideCompanies();
self[company](true);
self.allComp(false);
self.selectedCompany(company);
while(self.chart.series.length > 0){
self.chart.series[0].remove(true);
}
self.chart.addSeries(companyChart[company]);
}
this.allCompanies = function(){
self.hideCompanies();
self.allComp(true);
self.selectedCompany('All Companies');
self.chart.addSeries(companyChart['All Companies']);
$.each(companyData, function(index, company) {
self.chart.addSeries(companyChart[company]);
});
}
this.hideCompanies = function(){
$.each(companyData, function(i, c){
self[c](false);
});
while(self.chart.series.length > 0){
self.chart.series[0].remove(true);
}
}
}
It controls adding series to a high charts chart, based on whichever company is selected.
In my partial, I have the some HTML, and then the following javascript code block:
<!--SCRIPTS-->
<script type="text/javascript">
<% companies = current_user.list_of_companies %>
<% funding_date = current_user.first_funding_date * 1000 %>
var companyData = <%= companies.map(&:name).to_json.html_safe %>;
var companyChart = {};
companyChart['All Companies'] = {
name: 'Total Portfolio',
pointInterval: <%= 1.day * 1000 %>,
pointStart: <%=funding_date %>,
data: <%= current_user.portfolio_values.group("portfolio_values.day").select("portfolio_values.day, SUM(portfolio_values.value) as totals").map(&:totals).collect{|x| x.to_i} %>
}
<% companies.each do |company|%>
companyChart['<%= company.name %>'] = {
name: '<%= company.name %>',
pointInterval: <%= 1.day * 1000 %>,
pointStart: <%= funding_date %>,
data: <%= current_user.portfolio_values.where(:company_id => company.id).map(&:value).collect{|x| x.to_i} %>
}
<% end %>
var vm = new portfolioViewModel();
ko.applyBindings(vm);
vm.chart = new Highcharts.StockChart({
chart: {
renderTo: 'chart1',
backgroundColor: 'transparent',
zoomType: 'xy',
type: 'areaspline',
style: {
color: '#ffffff'
}
},
labels : {
style: {
color: 'red'
}
},
colors: [
'#ea00ff',
'#229aff',
'#ff4e00',
'#ea00ff',
'#229aff',
'#ff4e00',
'#ea00ff',
'#229aff',
'#ff4e00',
'#ea00ff',
'#229aff',
'#ff4e00'
],
credits: {
enabled: false
},
rangeSelector: {
enabled: false,
buttons: [{
type: 'month',
count: 1,
text: '1m'
}, {
type: 'ytd',
text: 'YTD'
}, {
type: 'all',
text: 'All'
}],
buttonTheme: { // styles for the buttons
fill: 'none',
stroke: 'none',
style: {
color: '#fff',
fontWeight: 'bold'
},
states: {
hover: {
stroke: 'none',
fill: 'black'
},
select: {
stroke: 'none',
fill: 'black',
style: {
color: 'white'
}
}
}
},
inputStyle: {
color: '#fff',
fontWeight: 'bold',
borderColor:'transparent',
background: 'transparent'
},
labelStyle: {
color: 'silver',
fontWeight: 'bold'
}
},
navigator: {
enabled: false,
},
plotOptions : {
areaspline : {
lineWidth : 2,
fillOpacity : .2,
shadow:true,
marker : {
enabled : false,
symbol: 'circle'
}
}
},
yAxis: {
alternateGridColor: 'rgba(0,0,0,0.1)',
gridLineColor: 'rgba(0,0,0,0.3)',
lineColor: 'rgba(0,0,0,0.3)',
lineWidth: 1,
labels: {
style: {
color: 'rgba(255,255,255,0.6)',
fontWeight: 'bold'
}
}
},
xAxis: {
gridLineWidth: 1,
gridLineColor: 'rgba(0,0,0,0.3)',
type: 'datetime',
lineColor: 'rgba(0,0,0,0.3)',
labels: {
style: {
color: 'rgba(255,255,255,0.6)',
fontWeight: 'bold'
}
}
},
scrollbar : {
enabled : false
},
series: vm.chartSeries()
});
</script>
<!--SCRIPTS-->
Sometimes the bindings are applied and the scripts load with the partial, but many times they do not. When they do not load with the remote call to the partial (even though the HTML comes through) the script block will be completely missing it seems.
I'm not even sure how to start debugging this. Does anyone see any obvious mistakes? I'm very new to javascript.

Typically, if there's a javascript error of any kind that stops the execution of later javascript, that will prevent your ko model from loading, or cause it to load only part way. I recommend using Firebug with Firefox, or something similar, to check for the javascript error causing the problem.
Also, the 'gon' gem is a good way to get information from your rails model into your javascript. I also like using the rabl gem with .json.rabl templates for ajax requests to update the knockout model.

Related

Highcharts not showing up in ruby web app

Will someone tell me why my high charts aren't coming up on my ruby sinatra web application. I'm trying to pull data from my dynamodb table and put that into charts. I downloaded my dynamodb items into a csv then converted that to a json file hoping that would help. I can go on high charts website and do a demo and it loads in my website just not mine.
This is my synchronize-chart.js
$(function() {
$('#synchronized').bind('mousemove touchmove', function(e) {
var chart,
point,
i;
for (i = 0; i < Highcharts.charts.length; i = i + 1) {
chart = Highcharts.charts[i];
if(chart.renderTo.className != 'chart'){
continue;
}
e = chart.pointer.normalize(e); // Find coordinates within the chart
point = chart.series[0].searchPoint(e, true); // Get the hovered point
if (point) {
point.onMouseOver(); // Show the hover marker
chart.tooltip.refresh(point); // Show the tooltip
chart.xAxis[0].drawCrosshair(e, point); // Show the crosshair
}
}
});
/**
* Override the reset function, we do not need to hide the tooltips and crosshairs.
*/
Highcharts.Pointer.prototype.reset = function() {
return undefined;
};
/**
* Synchronize zooming through the setExtremes event handler.
*/
function syncExtremes(e) {
var thisChart = this.chart;
if (e.trigger !== 'syncExtremes') { // Prevent feedback loop
Highcharts.each(Highcharts.charts, function(chart) {
if (chart !== thisChart) {
if (chart.xAxis[0].setExtremes) { // It is null while updating
chart.xAxis[0].setExtremes(e.min, e.max, undefined, false, {
trigger: 'syncExtremes'
});
}
}
});
}
}
// Get the data. The contents of the data file can be viewed at
// https://github.com/highcharts/highcharts/blob/master/samples/data/activity.json
$.getJSON('/covertcsv.json', function(activity) {
$.each(activity.datasets, function(i, dataset) {
// Add X values
dataset.data = Highcharts.map(dataset.data, function(val, j) {
return [activity.xData[j], val];
});
$('<div class="chart">')
.appendTo('#synchronized')
.highcharts({
chart: {
marginLeft: 40, // Keep all charts left aligned
spacingTop: 20,
spacingBottom: 20,
zoomType: 'x'
},
title: {
text: dataset.name,
align: 'left',
margin: 0,
x: 30
},
credits: {
enabled: false
},
legend: {
enabled: false
},
xAxis: {
crosshair: true,
events: {
setExtremes: syncExtremes
},
type: 'datetime'
},
yAxis: {
title: {
text: null
}
},
tooltip: {
positioner: function() {
return {
x: this.chart.chartWidth - this.label.width, // right aligned
y: -1 // align to title
};
},
borderWidth: 0,
backgroundColor: 'none',
//pointFormat: '{point.y}',
pointFormat: '<span style="font-size: 10px">{point.x:%e. %b \'%y %H:%M:%S}</span> {point.y}',
headerFormat: '',
shadow: false,
style: {
fontSize: '18px'
},
valueDecimals: dataset.valueDecimals
},
series: [{
data: dataset.data,
name: dataset.name,
type: dataset.type,
color: Highcharts.getOptions().colors[i],
fillOpacity: 0.3,
tooltip: {
valueSuffix: ' ' + dataset.unit
}
}]
});
});
});
});
Water-level-chart.js
$(function() {
var gaugeOptions = {
chart: {
type: 'solidgauge'
},
title: null,
pane: {
center: ['50%', '85%'],
size: '140%',
startAngle: -90,
endAngle: 90,
background: {
backgroundColor: (Highcharts.theme && Highcharts.theme.background2) || '#EEE',
innerRadius: '60%',
outerRadius: '100%',
shape: 'arc'
}
},
tooltip: {
enabled: false
},
// the value axis
yAxis: {
stops: [
[0.1, '#DF5353'], // red
[0.5, '#DDDF0D'], // yellow
[0.6, '#55BF3B'] // green
],
lineWidth: 0,
minorTickInterval: null,
tickPixelInterval: 400,
tickWidth: 0,
title: {
y: -70
},
labels: {
y: 16
}
},
plotOptions: {
solidgauge: {
dataLabels: {
y: 5,
borderWidth: 0,
useHTML: true
}
}
}
};
$.getJSON('/convertcsv.json', function(data) {
// The speed gauge
$('#container-speed').highcharts(Highcharts.merge(gaugeOptions, {
yAxis: {
min: 0,
max: 500,
title: {
text: 'Water Level'
}
},
credits: {
enabled: false
},
series: [{
name: 'Water Level',
data: [data.waterLevel],
dataLabels: {
format: '<div style="text-align:center"><span style="font-size:25px;color:' +
((Highcharts.theme && Highcharts.theme.contrastTextColor) || 'black') + '">{y}</span><br/>' +
'<span style="font-size:12px;color:silver">water left</span></div>'
},
tooltip: {
valueSuffix: ''
}
}]
})); // container-speed end
}); // getJson end
});
item.rb
class Item
require 'dynamoid'
include Dynamoid::Document
table name: :sensor, key: :key, :read_capacity => 5, :write_capacity => 5
field :timestamp, :integer
field :payload, :serialized
def self.chart_values
x_data = []
temperatures = []
humidities = []
soil_moistures = []
# not an efective way to do
Item.all.each do |item|
x_data << item.timestamp
temperatures << (item.payload['temp'].to_f || 0)
humidities << (item.payload['hum'].to_f || 0)
soil_moistures << (item.payload['sol'].to_f || 0)
end
highcharts_value(x_data, temperatures, humidities, soil_moistures)
end
def self.highcharts_value(x_axis, temp, hum, soil)
{
xData: x_axis,
datasets: [
{
name: 'Temperature',
data: temp,
unit: '°C',
type: 'area',
valueDecimals: 1
},
{
name: 'Humidity',
data: hum,
unit: '%',
type: 'area',
valueDecimals: 1
},
{
name: 'Soil Moisture',
data: soil,
unit: '',
type: 'area',
valueDecimals: 0
}
]
}
end
end
index.haml
%head
%script{type: "text/javascript", src: url('/javascripts/jquery.min.js')}
%script{type: "text/javascript", src: url('/javascripts/highcharts.js')}
%script{type: "text/javascript", src: url('/javascripts/highcharts-more.js')}
%script{type: "text/javascript", src: url('/javascripts/solid-gauge.js')}
%script{type: "text/javascript", src: url('/javascripts/synchronized-charts.js')}
%script{type: "text/javascript", src: url('/javascripts/water-level-chart.js')}
%script{type: "text/javascript", src: url('/javascripts/water-pump.js')}
%link{rel: :stylesheet, type: :"text/css", href: url('/stylesheets/default.css')}
#container
#synchronized
.gauge
#container-speed
.pump-control
%form{method: :post, action: '/take-action', id: 'action-form' }
%input{type: 'hidden', name: 'action', value: 'start', id: 'action_input'}
%span{id: 'pumper', onclick: 'takeAction()'}
start
After checking the browser console it says
jquery.min.js:2 GET http://localhost:4567/convertcsv.json 404 (Not Found)
send # jquery.min.js:2
ajax # jquery.min.js:2
p.(anonymous function) # jquery.min.js:2
getJSON # jquery.min.js:2
(anonymous) # synchronized-charts.js:60
k # jquery.min.js:2
fireWith # jquery.min.js:2
ready # jquery.min.js:2
D # jquery.min.js:2

drilldown maps and funnell charts on the same page using highcharts

I am having some issues with the combination of drilldown maps with funnell charts using highcharts . My requirement is : I need to display drilldown maps in one div and funnell charts in another div .
But only drill down maps rendering correctly on the page, but funnell chart not rendering.
Javascript used :
<script src="http://code.highcharts.com/maps/highmaps.js"></script>
<script src="http://code.highcharts.com/maps/modules/data.js"></script>
<script src="http://code.highcharts.com/maps/modules/drilldown.js"></script>
<script src="http://code.highcharts.com/mapdata/countries/us/us-all.js"></script>
<script src="http://code.highcharts.com/maps/modules/exporting.js"></script>
<script src="http://code.highcharts.com/mapdata/custom/world.js"></script>
<script src="http://code.highcharts.com/highcharts.js"></script>
<script src="http://code.highcharts.com/modules/funnel.js"></script>
<script src="http://code.highcharts.com/modules/exporting.js"></script>
<script src="http://code.highcharts.com/adapters/standalone-framework.js"></script>
HTML DIV section :
<div id="drilldownmap">
<div id="funnell">
Data :
$(function () {
var data = Highcharts.geojson(Highcharts.maps['countries/us/us-all']),
// Some responsiveness
small = $('#drilldownmap').width() < 400;
// Set drilldown pointers
$.each(data, function (i) {
this.drilldown = this.properties['hc-key'];
this.value = i; // Non-random bogus data
});
// Instanciate the map
$('#drilldownmap').highcharts('Map', {
chart : {
events: {
drilldown: function (e) {
if (!e.seriesOptions) {
var chart = this,
mapKey = 'countries/us/' + e.point.drilldown + '-all',
// Handle error, the timeout is cleared on success
fail = setTimeout(function () {
if (!Highcharts.maps[mapKey]) {
chart.showLoading('<i class="icon-frown"></i> Failed loading ' + e.point.name);
fail = setTimeout(function () {
chart.hideLoading();
}, 1000);
}
}, 3000);
// Show the spinner
chart.showLoading('<i class="icon-spinner icon-spin icon-3x"></i>'); // Font Awesome spinner
// Load the drilldown map
$.getScript('http://code.highcharts.com/mapdata/' + mapKey + '.js', function () {
data = Highcharts.geojson(Highcharts.maps[mapKey]);
// Set a non-random bogus value
$.each(data, function (i) {
this.value = i;
});
// Hide loading and add series
chart.hideLoading();
clearTimeout(fail);
chart.addSeriesAsDrilldown(e.point, {
name: e.point.name,
data: data,
dataLabels: {
enabled: true,
format: '{point.name}'
}
});
});
}
this.setTitle(null, { text: e.point.name });
},
drillup: function () {
this.setTitle(null, { text: 'USA' });
}
}
},
title : {
text : ''
},
subtitle: {
text: 'USA',
floating: true,
align: 'right',
y: 50,
style: {
fontSize: '16px'
}
},
legend: small ? {} : {
layout: 'vertical',
align: 'right',
verticalAlign: 'middle'
},
colorAxis: {
min: 0,
minColor: '#E6E7E8',
maxColor: '#005645'
},
mapNavigation: {
enabled: true,
buttonOptions: {
verticalAlign: 'bottom'
}
},
plotOptions: {
map: {
states: {
hover: {
color: '#EEDD66'
}
}
}
},
series : [{
data : data,
name: 'USA',
dataLabels: {
enabled: true,
format: '{point.properties.postal-code}'
}
}],
drilldown: {
//series: drilldownSeries,
activeDataLabelStyle: {
color: 'white',
textDecoration: 'none'
},
drillUpButton: {
relativeTo: 'spacingBox',
position: {
x: 0,
y: 60
}
}
}
});
$('#funnell').highcharts({
chart: {
type: 'funnel',
marginRight: 100
},
title: {
text: 'Conversion funnel',
x: -50
},
plotOptions: {
series: {
dataLabels: {
enabled: true,
format: '<b>{point.name}</b> ({point.y:,.0f})',
color: (Highcharts.theme && Highcharts.theme.contrastTextColor) || 'black',
softConnector: true
},
neckWidth: '30%',
neckHeight: '25%'
//-- Other available options
// height: pixels or percent
// width: pixels or percent
}
},
legend: {
enabled: true
},
series: [{
name: 'Unique users',
data: [
['Website visits', 15558],
['Carts', 2017],
['Checkouts', 608],
['Orders', 368]
]
}]
});
});
It would be great if someone could help me to resolve this issue??
Thanks.
I think highmaps.js is causing a conflict here. Use
<script src="http://github.highcharts.com/modules/map.src.js"></script>
instead of
<script src="http://code.highcharts.com/maps/highmaps.js"></script>
And place
<script src="http://code.highcharts.com/highcharts.js"></script>
before
<script src="http://github.highcharts.com/modules/map.src.js"></script>
The complete list of script refs in <head> tag should look like this:
<script src="http://code.highcharts.com/highcharts.js"></script>
<script src="http://github.highcharts.com/modules/map.src.js"></script>
<script src="http://code.highcharts.com/maps/modules/data.js"></script>
<script src="http://code.highcharts.com/maps/modules/drilldown.js"></script>
<script src="http://code.highcharts.com/mapdata/countries/us/us-all.js"></script>
<script src="http://code.highcharts.com/maps/modules/exporting.js"></script>
<script src="http://code.highcharts.com/mapdata/custom/world.js"></script>
<script src="http://code.highcharts.com/modules/funnel.js"></script>
<script src="http://code.highcharts.com/modules/exporting.js"></script>
<script src="http://code.highcharts.com/adapters/standalone-framework.js"></script>
This should get the job done.

Getting error when try to use external parameter to generate chart

I retrieve JSON data from server and put it in Highchart as series.I am facing this error:
Error: Invalid value for attribute y="NaN" highcharts.js : 9
The error happen if I send chartSeries parameter from callChart function.But if I copy chartSeries value and put it directly inside drawChart it able to display the chart.However there no problem for other parameter such chartCategory and chartTitle.
Here is my code:
function callChart(){
for (var i in jsonData){
console.log('#i '+i);
console.log('#subSegment i '+jsonData[i].subSegment);
var chartTitle= jsonData[i].subSegment;
console.log('categories '+ jsonData[i].categories);
var chartCategory= jsonData[i].categories;
console.log('series '+ JSON.stringify(jsonData[i].series));
var chartSeries=JSON.stringify(jsonData[i].series);
drawChart($('.chartContainer'),chartSeries,chartCategory,chartTitle);
break;}}
Here is the code of drawChart;
function drawChart(container,chartSeries,chartCategory,chartTitle) {
console.log('# test');
console.log('# chartSeries='+chartSeries);
console.log('# chartCategory='+chartCategory);
console.log('# chartTitle='+chartTitle);
//it works if I put the chartSeries directly here
/*chartSeries=[{"type":"column","stack":null,"pointPlacement":null,"name":"HDD","linkedTo":null,"id":"hdd","data":[30,30,70,90,37,200],"color":"greenColor","borderWidth":null},{"type":"column","stack":"old","pointPlacement":null,"name":"SSHD","linkedTo":null,"id":"sshd","data":[0,100,40,90,60,90],"color":"yellowColor","borderWidth":null},{"type":"column","stack":"old","pointPlacement":null,"name":"SSD","linkedTo":null,"id":"ssd","data":[50,100,40,90,60,100],"color":"blueColor","borderWidth":null},{"type":"column","stack":"forecast","pointPlacement":null,"name":"HDD","linkedTo":"hdd","id":null,"data":[30,80,40,100,60,90],"color":"greenColor","borderWidth":null},{"type":"column","stack":"forecast","pointPlacement":null,"name":"SSD","linkedTo":"ssd","id":null,"data":[30,80,40,100,60,90],"color":"yellowCollor","borderWidth":null},{"type":"spline","stack":null,"pointPlacement":null,"name":"Share","linkedTo":null,"id":null,"data":[30,80,40,100,60,90],"color":"black","borderWidth":null}] ;
*/
if (!container.length) {
return;
}
var chart = new Highcharts.Chart({
tooltip: {
enabled: true
},
credits: {
enabled: false
},
chart: {
renderTo: container[0],
style: {
fontFamily: '"Arial", "Helvetica", "sans-serif"',
fontSize: '12px',
fontWeight: 'bold'
},
marginLeft:60,
marginRight:65
},
title: {
text: chartTitle
},
xAxis: {
categories: chartCategory
},
yAxis: [{
min: 0,
title: {
text: 'Units in 000\' s'
},
stackLabels: {
enabled: false,
style: {
fontWeight: 'bold',
color: (Highcharts.theme && Highcharts.theme.textColor) || 'gray'
}
}
}, { // Secondary yAxis
title: {
text: 'Share',
style: {
color: Highcharts.getOptions().colors[0]
}
},
labels: {
format: '{value} %',
style: {
color: Highcharts.getOptions().colors[0]
}
},
opposite: true,
min: 0,
max: 100
}],
legend: {
enabled:false
},
plotOptions: {
column: {
grouping: false,
stacking: 'normal',
pointWidth:30
},
series:{shadow:false}
}
,series:chartSeries
});
}
Thanks alot.
Okay, I found it already.
Instead pass JSON.stringify(jsonData[i].series) , directly pass jsonData[i].series.
Thanks

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

Loading JQuery dynamically but highcharts fails

I am not really a javascript programmer but I have been struggling for a long time with this problem - any help would be very much appreciated.
In the following jsfiddle - if Jquery is selected from the frameworks and extensions tab the highcharts chart works fine. But the point of the code is I need to dynamically load a different jquery version - to use the chart as a widget of sorts. But changing it to no library (pure JS) the chart does not load.
http://jsfiddle.net/hgera000/JcVLQ/3/
A large part of my code I'm getting from here:
http://alexmarandon.com/articles/web_widget_jquery/
Thanks very much
(function() {
// Localize jQuery variable
var jQuery;
/******** Load jQuery if not present *********/
if (window.jQuery === undefined || window.jQuery.fn.jquery !== '1.7.2') {
var script_tag = document.createElement('script');
script_tag.setAttribute("type","text/javascript");
script_tag.setAttribute("src",
"http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js");
if (script_tag.readyState) {
script_tag.onreadystatechange = function () { // For old versions of IE
if (this.readyState == 'complete' || this.readyState == 'loaded') {
scriptLoadHandler();
}
};
} else {
script_tag.onload = scriptLoadHandler;
}
// Try to find the head, otherwise default to the documentElement
(document.getElementsByTagName("head")[0] || document.documentElement).appendChild(script_tag);
} else {
// The jQuery version on the window is the one we want to use
jQuery = window.jQuery;
main();
}
/******** Called once jQuery has loaded ******/
function scriptLoadHandler() {
// Restore $ and window.jQuery to their previous values and store the
// new jQuery in our local jQuery variable
jQuery = window.jQuery.noConflict(true);
// Call our main function
main();
}
/******** Our main function ********/
function main() {
var chart;
jQuery(document).ready(function($) {
/******* Load CSS *******/
var css_link = $("<link>", {
rel: "stylesheet",
type: "text/css",
href: "style.css"
});
css_link.appendTo('head');
/******* Load HTML *******/
chart = new Highcharts.Chart({
credits: {
enabled: true,
text: '',
href: ''
},
chart: {
renderTo: 'bm-container',
events: {
click: function () {
window.open('http://www.betmetrix.com', '_blank')
},
},
backgroundColor: '#FFFFFF',
zoomType: 'xy',
type: 'line',
marginLeft: 40,
marginRight: 40,
marginBottom: 40,
},
title: {
text: 'Election Worm',
x: -5,
style: {
color: '#000000',
fontWeight: 'bold',
fontSize: '17pt'
}
},
subtitle: {
text: 'Estimated Probability of Victory',
x: -5,
style: {
color: '#000000',
//fontWeight: 'bold',
fontSize: '13pt'
}
},
xAxis: {
type: 'datetime',
minRange: 7 * 24 * 3600000, // 1 week
dateTimeLabelFormats: {
second: '%H:%M:%S',
minute: '%H:%M',
hour: '%H:%M',
day: '%e %b',
week: '%e %b',
month: '%b \'%y',
year: '%Y'
},
//max: lnp[lnp.length-1][0]+604800000,
//tickInterval: 24*3600*1000*120,
//showFirstLabel: false,
minTickInterval: 1 * 24 * 3600000, //1 day
//maxTickInterval: 1 * 24 * 3600000*365, //30 day
startOnTick: false,
labels: {
style: {
color: '#969696',
//fontWeight: 'bold',
fontSize: '11pt'
}
}
},
yAxis: [{
//LHS axis
title: {
text: '%',
align: 'high',
rotation: 0,
offset: 10,
style: {
color: '#969696',
//fontWeight: 'bold',
fontSize: '11pt'
}
},
labels: {
style: {
color: '#969696',
//fontWeight: 'bold',
fontSize: '11pt'
}
},
showLastLabel: false,
showFirstLabel: false,
minRange: 3,
minTickInterval: 1,
min: 0,
max: 100,
opposite: false,
startOnTick: true,
//tickInterval: 5,
allowDecimals: false
}, {
//RHS axis
title: {
text: '%',
align: 'high',
rotation: 0,
offset: 20,
style: {
color: '#969696',
//fontWeight: 'bold',
fontSize: '11pt'
}
},
linkedTo: 0,
labels: {
style: {
color: '#969696',
//fontWeight: 'bold',
fontSize: '11pt'
}
},
showLastLabel: false,
minTickInterval: 1,
minRange: 3,
showFirstLabel: false,
startOnTick: true,
min: 0,
max: 100,
opposite: true,
//tickInterval: 10,
allowDecimals: false
}],
tooltip: {
xDateFormat: '%d-%b-%Y %l%P', //'%d-%b-%Y %l%P'
valueSuffix: '%',
valueDecimals: 1
//formatter: function () {
// return this.x + '<br/><b>' + this.series.name + ':' + '</b>' + this.y + '%';
//}
},
legend: {
enabled: false
// layout: 'vertical',
// align: 'right',
// verticalAlign: 'left',
// x: -20,
// y: 10,
// borderWidth: 0
},
series: [{
name: 'Coalition',
data: lnp,
marker: {
enabled: false
},
yaxis: 0
}, {
name: 'ALP',
data: alp,
marker: {
enabled: false
},
yaxis: 0
}],
exporting: {
enabled: false
}
});
});
}
})(); // We call our anonymous function immediately
Although the alexmarandon.com web widget tutorial mentions other libraries, maybe your case would be better suited with an all dynamic "chain load" approach. Once the jquery dynamic load is complete, don't go directly to main(), but instead move on and chain load Highcharts dynamically as well. Add this one more function, remove static, external reference to Highcharts.js, and then replace the call back to scriptLoadHandler() with a call to this chainLoadHighchharts() function, which itself will then pass on to the original scriptLoadHandler().
function chainLoadHighCharts() {
var Highcharts;
/******** Ok, /now/ dynamically load up highchart too... *********/
if (window.Highcharts === undefined) {
var script_tag = document.createElement('script');
script_tag.setAttribute("type", "text/javascript");
script_tag.setAttribute("src",
"http://code.highcharts.com/highcharts.js");
if (script_tag.readyState) {
script_tag.onreadystatechange = function () { // For old versions of IE
if (this.readyState == 'complete' || this.readyState == 'loaded') {
scriptLoadHandler(); //here is the call that was orginally called directly from the jquery dynamic load.
}
};
} else {
script_tag.onload = scriptLoadHandler;
}
// Try to find the head, otherwise default to the documentElement
(document.getElementsByTagName("head")[0] || document.documentElement).appendChild(script_tag);
} else {
scriptLoadHandler();
// script_tag.setAttribute("src","http://code.highcharts.com/modules/exporting.js");
}
}
Still needs a bit of tightening, but it ran without error for me on jsfiddle.
http://jsfiddle.net/JcVLQ/5/

Categories

Resources