ReferenceError: HighCharts is not defined - javascript

I'm rendering a chart using highstocks on my rails application on a index.html.erb file, however when I try to load the chart, I get the following error on the firebug console,
ReferenceError: HighCharts is not defined
new HighCharts.Chart({
My index.html.erb file is as follows
<div id="quotes_chart", style="width=560px; height:300px;">
<script>
$(function(){
new HighCharts.Chart({
chart : {
renderTo: "quotes_chart"
},
title : {
text: "Daily trades"
},
xAxis : {
type: "datetime"
},
yAxis : {
title: {
text: "Shillings"
}
},
tooltip : {
formatter: function(){
return HighCharts.dateFormat("%B %e, %Y", this.x) + ': ' + "Kshs" + Highcharts.numberFormat(this.y, 2);
}
},
series: [
<% { "Telecommunication" => StockQuote.telecomm, "Agriculture" => StockQuote.agric }.each do |name, prices|
%>
{
name: <%= name %>,
pointInterval: <%= 1.day * 1000 %>,
pointStart: <%= 2.weeks.ago.to_i * 1000 %>,
data: <%= (2.weeks.ago.to_date..Date.today).map { |date| StockQuote.price_on(date).to_f}.inspect%>
},
<% end %>
]
});
});
</script>
</div>
In my application.html.erb is as follows:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script src="components/highstock/highstock.js"></script>
<%= javascript_include_tag "jquery-1.11.0.min", "highcharts" %>
In my app assests/javascripts folder I have both the jquery-1.11.0.min.js and highcharts.js files as downloaded from highcharts.com
What might I be doing wrong?

var chart=null;
$(document).ready(function() {
chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
type: 'bar'
},
title: {
text: '${model.title}'
}
...
Set the chart to null because this error can occur due to multiple declaration that you may not be aware of. Assumption is all imports are correct

You need to load Highcharts only once, not twice as you have. So, I recommend to use only:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script src="components/highstock/highstock.js"></script>
Because Highstock includes all Highcharts options. Morever please take care about correct paths to your files, because it looks like a problem only with it.

Related

JavaScript code(JQuery) not display in rails app

I want to display chart in view in rails app. use this link http://jsfiddle.net/zz7pB/ contain chart
in application.html.erb and try it in view
<script src="http://code.highcharts.com/highcharts.js"></script>
<script src="http://code.highcharts.com/modules/exporting.js"></script>
in application.js
//= require_tree
//= require jquery
//= require jquery_ujs
//= require bootstrap
//= require chart ---> name of controller
chart.js in app -> assets -> javascripts
$(function () {
$(document).ready(function() {
Highcharts.setOptions({
global: {
useUTC: false
}
});
var chart;
$('#container').highcharts({
chart: {
type: 'line',
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);
}, 1000);
}
}
},
title: {
text: 'Live random data'
},
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() {
// generate an array of random data
var data = [],
time = (new Date()).getTime(),
i;
for (i = -19; i <= 0; i++) {
data.push({
x: time + i * 1000,
y: Math.random()
});
}
return data;
})()
}]
});
});
});
in index.html.erb
<div id="container" style="min-width: 310px; height: 400px; margin: 0 auto"></div>
i want display this chart in my app this all information. This live chart
when inspect element display div put not contain chart.
i read this Where should I place my jQuery code in my Ruby on Rails applications? but not solve it
This error appear in the console in the browser
EDITED:
Step 1
I created a new rails application and, Jquery-rails Gem added to the Gemfile.
Gemfile
gem 'jquery-rails', '~> 4.3', '>= 4.3.1'
application.js
//= require jquery
//= require jquery_ujs
And then run bundle install
Step 2
Downloaded HighchartJs and ExportingJs files and placed in assets/javascripts/plugins folder. And, These libraries are imported to application.js as below.
application.js
//= require plugins/highcharts
//= require plugins/exporting
Step 3
Created chart.js file and imported to application.js
//= require chart
Then paste your Js code in this file. All should work now.
Tips Please follow more tutorials to learn how to debug javascript with browser console.

Charts integration in active admin dashboard rails

My Dashboard
section "Graph", do
div do
render 'graph'
end
end
_graph.html.erb
<script type="text/javascript">
$(function(){
new Highcharts.Chart({
chart: {
renderTo: "charts"
},
title: {
text: "Orders"
},
xAxis: {
title: {
text: "X axis"
}
},
yAxis: {
title: {
text: "Y axis"
}
},
series: [{
data: [1,3,5,7]
}]
});
});
In which folder I place that _graph.html.erb so that it can loaded. is JavaScript in it works correctly after that?
Charts integration on active admin is pretty simple, all you have to use is get chartkick in your Gemfile.
Then in your dashboard.rb you can create another panel within a column and show your graph.
Example:
panel "Top stuff --all name-removed for brevity--" do
# line_chart Content.pluck("download").uniq.map { |c| { title: c, data: Content.where(download: c).group_by_day(:updated_at, format: "%B %d, %Y").count } }, discrete: true
# column_chart Content.group_by_hour_of_day(:updated_at, format: "%l %P").order(:download).count, {library: {title:'Downloads for all providers'}}
# column_chart Content.group(:title).order('download DESC').limit(5).sum(:download)
bar_chart Content.group(:title).order('download DESC').limit(5).sum(:download) ,{library: {title:'Top 5 Downloads'}}
##
# line_chart result.each(:as => :hash) { |item|
# {name: item.title, data: item.sum_download.count}
# }
end
end

Rails array to javascript in HighCharts, Highstock, 2 dimensional array

In my app users record their weight and the date that weight belongs to. I want that data displayed in a HighStock line graph. Should be very simple, but I've been working on this (partially) over the past 2 months. I've looked at a bunch of different things and I can't get this to work.
The exact data I'd like displayed is the actual line in the line graph to be their weight, y-axis will be their weight, x-axis will be the date that the user entered for that weight.
i.e. user enters their weight in the form for yesterday as 135 and the date they put in with the form is 12/3/2012.
Don't know if it matters but a User has_many weights, a weight belongs_to a user.
Here is what I have and I'm getting a bunch of different errors. I'm definitely missing/not understanding something here:
Weight Model:
class Weight < ActiveRecord::Base
def user_weight_series(user, weight)
weights_by_weight_date = Weights.select("date(weight_date) as dater, content as weights")
weights_by_weight_date.map do |record|
parts = %w[%Y %m %d].map{ |s| record.dater.send(s) }
"[Date.UTC(#{parts.join(',')}), #{record.weights}]"
end
end
application.html.erb
<script type="text/javascript">
$(function () {
var chart;
$(document).ready(function() {
window.chart = new Highcharts.StockChart({
chart: {
renderTo: 'weight_chart',
type: 'line',
marginRight: 20,
marginBottom: 25
},
title: {
text: 'Your Weight Over Time',
x: -20 //center
},
yAxis: {
title: {
text: 'Weight'
},
plotLines: [{
value: 0,
width: 1,
color: '#808080'
}]
},
legend: {
layout: 'vertical',
align: 'center',
verticalAlign: 'bottom',
x: -10,
y: 100,
borderWidth: 0
},
scrollbar: {
enabled: true
},
rangeSelector : {
selected : 1
},
credits: {
enabled: false
},
series: [{
tickInterval: <%= 1.day * 1000 %>,
pointStart: <%= 3.weeks.ago.at_midnight.to_i * 1000 %>,
name: 'Weight',
data: [ <%= current_user.user_weight_series(user, weight).join(", ") %> ],
}]
},
function(chart){
// apply the date pickers
setTimeout(function(){
$('input.highcharts-range-selector', $('#'+chart.options.chart.renderTo))
.datepicker()
},0)
});
});
});
What's the best way to do this? Thank you in advance!
Here is the process I use, along with some tips to get you started:
Work backwards from the desired display you want to create, using dummy json data to populate the chart.
Figure out how to create a ruby hash of your real database data that matches the dummy json data series. For the timestamps, convert them to a highcharts-readable format like this:
SOME_DATE.to_time.to_i * 1000
Have one of your controllers render the resulting ruby hash as json.
def some_controller_method
#chart_data_series = [] // your desired series here
respond_to do |format|
format.json { render :json => #chart_data_series }
end
end
Read this json from its appropriate page and pass it into your chart series. One way is to use d3:
function buildChart(){
d3.json("/path/to/your/data.json", function(error, json_data) {
$('#chart_container').highcharts({
chart: {type: 'column'},
// options, options, etc
series: json_data,
// options, options, etc
});
});
});

highcharts: issues

I'm making an app with highcharts, after having many problems I finally make plotted but now takes the correct data but I need to make some adjustments.
for example if an user registers a new log on the same day it should take the cost of the log and add it to the logs of the same day or simply show if there are no more, I follow the railcast episode 223 and helpme a little. but my issue is: when I add a new log it create a new bar:
(there are only 2 logs, I'm gonna create a new log)
here is that my app do.
also I need to fix the datetime, here is my code:
$(function () {
new Highcharts.Chart({
chart: { renderTo: 'foo_chart',defaultSeriesType: 'column' },
title: { text: 'tanking costs daily' },
xAxis: { type: 'datetime' },
yAxis: {
title: { text: 'cost' }
},
tooltip: {
formatter: function () {
return Highcharts.dateFormat("%B %e %Y", this.x) + ': ' + '$' + Highcharts.numberFormat(this.y, 2);
}
},
series: [{
name: 'Days',
pointInterval: <%= 1.day * 1000 %>,
pointStart: <%= 1.weeks.ago.at_midnight.to_i * 1000 %>,
data:[
<% for tankinglog in #tankinglog %>
<%= "(" + tankinglog.cost.to_f.round(2).to_s + "),"%>
<% end %>
]
}]
});
});
if you see the list on the picture I have 3 logs...the last 2 logs have the same date these must appear in the same bar with the sum of their costs
Your question is very confusing. You want all the data summed into one bar? A new bar is created for each number you have in the data list. So your for-each loop is creating a new bar for each item in #tankinglog. The solution is to sum what's required into one number, then add it to the list.
I'm not sure exactly what you're asking because your question is poor but here are all the values summed into one bar.
$(function () {
new Highcharts.Chart({
chart: { renderTo: 'foo_chart',defaultSeriesType: 'column' },
title: { text: 'tanking costs daily' },
xAxis: { type: 'datetime' },
yAxis: {
title: { text: 'cost' }
},
tooltip: {
formatter: function () {
return Highcharts.dateFormat("%B %e %Y", this.x) + ': ' + '$' + Highcharts.numberFormat(this.y, 2);
}
},
series: [{
name: 'Days',
pointInterval: <%= 1.day * 1000 %>,
pointStart: <%= 1.weeks.ago.at_midnight.to_i * 1000 %>,
data:[
<%
result = 0;
for tankinglog in #tankinglog
result += tankinglog.cost.to_f
end %>
<%= result.round(2).to_s %>
]
}]
});
});

How to I determine the value of a bar in a bar chart (Highchart) on user click?

Currently I have a Highchart that renders according to data in my database. I also currently have a table that renders with the correct values when I pass in a value such as "A" or "C" manually, but I'd like the table to render according to an onClick event, when a user clicks on a bar in my Highchart.
For each corresponding value below, such as #a_sum, I have an array called #a with string values in it that will be passed into the chart.
I've Googled around without much luck. I'm wondering how I get the value of the bar in the char when a user clicks on that specific bar.
Any help would be hugely appreciated.
<script type="text/javascript" charset="utf-8">
var chart1; // globally available
$(document).ready(function () {
var chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
type: 'bar'
},
title : {
text: "Most Effective Referral Sources"
},
xAxis: {
categories: ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L']
},
yAxis: {
},
legend: {
layout: 'vertical',
floating: true,
backgroundColor: '#FFFFFF',
align: 'right',
verticalAlign: 'top',
y: 60,
x: -60
},
tooltip: {
formatter: function() {
return '<b>'+ this.series.name +'</b><br/>'+
this.x +': '+ this.y;
}
},
plotOptions: {
},
series: [{
data: [<%= #a_sum %>, <%= #b_sum %>, <%= #c_sum %>, <%= #d_sum %>, <%= #e_sum %>, <%= #f_sum %>, <%= #g_sum %>, <%= #h_sum %>, <%= #i_sum %>, <%= #j_sum %>, <%= #k_sum %>, <%= #l_sum %>]
}]
});
});
</script>
It seems like what you want (if I understand you question correctly) is to implement the event in the plotOptions above:
http://www.highcharts.com/ref/#plotOptions-column-point-events--click
plotOptions: {
column: {
point: {
events: {
click: function() {
// use this to trigger showing/hiding the specific table you need
console.log(this)
}
}
}
}
}
For example, this is a sample of the console log I got:
Lc
_high: 417
...
series: c
...
x: 20
y: 33
__proto__: Object
With this.series you should be able to get the parameters on the series whose column you click, and then call your "enableTableForDataSeries" function to enable the specific data series.

Categories