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.
Related
This is my first time using highcharts alongside with jade and the MEAN stack. I am able to get the chart to work on a jsfiddle, but it will not display anything inside of the div when running locally.
this is the jsfiddle I used jade-lang to convert the jade into html so I would be able to put it into jsfiddle.
<div id="chartcon" style="min-width: 310px; height:400px; margin 0 auto"></div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js" type="text/javascript"></script>
<script src="http://code.highcharts.com/highcharts.js" type="text/javascript"></script>
<script src="http://code.highchart.com/modules/exporting.js" type="text/javascript"></script>
$(function() {
$('#chartcon').highcharts({
chart: {
type: 'column'
},
title: {
text: 'colum chart w/ neg values'
},
xAxis: {
categories: ['Apples','Oranges', 'Pears']
},
credits: {
enabled: false
},
series: [{
name: 'John',
data: [5,3,4]
}, {
name: 'Jane',
data: [2,-2,-3]
}, {
name: 'Joe',
data: [3,4,5]
}]
});
});
I am trying to do this in a single jade file, which I have been thinking may be the problem (I can't find to much on using jade with highcharts so this leads me to think it may not be compatible?)
I'm trying to generate a heatmap using data inserted by gon.
The frame for the chart is generated correctly in the browser, but the chart is missing, just blank.
and in the console I get:
Uncaught Highcharts error #17: www.highcharts.com/errors/17
which seems to be generated by the initSeries method in highcharts after a comment mentioning:
// No such series type
I'm using RoR4, with this in the Gemfile:
gem "highcharts-rails", "~> 3.0.0"
and this in the application.js:
//= require jquery
//= require jquery_ujs
//= require tether
//= require bootstrap-sprockets
//= require highcharts
//= require highcharts/highcharts-more
//= require turbolinks
//= require_tree .
my SLIM:
td
.card
.card-img-top(data-template-chart=true data-id=template.to_param)
my includes (from the compiled HTML):
<script src="/assets/highcharts.self-d34c91baaad4188e2d81d954aa38de43ec4916882f39d2d908f86d47a6e942b0.js?body=1" data-turbolinks-track="true"></script>
<script src="/assets/highcharts/highcharts-more.self-995bc649d8f9f68a0bb6bfb3242b35a20c494d716164fa0c93a74630b291113b.js?body=1" data-turbolinks-track="true"></script>
Inspecting the "sources" in the browser I can see both files being loaded
my coffeescript:
$(window).bind 'page:change', ->
initPage()
initPage= ->
$('[data-template-chart]').each( ->
curId = $(this).data("id")
data = gon.templates[curId]
$(this).highcharts
chart:
height: 150
width: 150
title: text: ''
xAxis:
showLastLabel: false
tickLength: 16
yAxis:
title: text: null
labels: format: '{value}:00'
minPadding: 0
maxPadding: 0
startOnTick: false
endOnTick: false
tickPositions: [0, 6, 12, 18, 24]
tickWidth: 1
min: 0
max: 23
reversed: true
colorAxis:
stops: [
[0, '#3060cf']
[0.5, '#fffbbc']
[0.9, '#c4463a']
[1, '#c4463a']
]
min: -15
max: 25
startOnTick: false
endOnTick: false
# labels: format: value
series: [
{
type: 'heatmap'
data: csv: data
borderWidth: 0
nullColor: '#EFEFEF'
colsize: 24 * 365
}
]
)
I'm guessing the issue is with the highcharts-more library, which is being loaded in the browser, but it doesn't seem to be available, and I'm guessing it's a problem with the javascript generated by coffeescript.
This is the compiled version:
(function() {
var initPage, update_form;
$(function() {
return initPage();
});
$(window).bind('page:change', function() {
return initPage();
});
update_form = function() {
var chart, end_quote, extremes, start_quote;
chart = $('#template_chart').highcharts();
extremes = chart.xAxis[0].getExtremes();
start_quote = Math.ceil(extremes.min);
end_quote = Math.floor(extremes.max);
$('#template_match_start_quote_id').val(gon.ids[start_quote]);
return $('#template_match_end_quote_id').val(gon.ids[end_quote]);
};
initPage = function() {
$('select[flexible_select]').flexible_select();
return $('#template_chart').each(function() {
var categories, prices;
prices = gon.prices;
categories = gon.ids;
return $(this).highcharts({
chart: {
zoomType: "x",
events: {
redraw: function() {
return update_form();
}
}
},
title: {
text: null
},
xAxis: {
categories: categories,
labels: {
enabled: false
}
},
yAxis: {
title: {
text: "Price",
style: {
color: Highcharts.getOptions().colors[1]
}
},
opposite: true
},
tooltip: {
shared: true
},
legend: {
enabled: false
},
credits: {
href: "http://www.pattern4all.com",
text: "source: www.pattern4all.com"
},
series: [
{
name: "Price",
data: prices,
type: "line",
marker: {
enabled: false
},
tooltip: {
valuePrefix: "$"
},
style: {
color: Highcharts.getOptions().colors[1]
}
}
]
});
});
};
}).call(this);
Turns out that:
I needed to add
//= require highcharts/modules/heatmap
to my application.js I thought it was a redundant inclusion, but apparently it's not.
Also the GEM readme, at: https://github.com/PerfectlyNormal/highcharts-rails mentions to install: gem "highcharts-rails", "~> 3.0.0" but 3.0.0 is not the latest version, I updated the gem inclusion to: gem "highcharts-rails", "~> 4.1.9", which is currently the latest, and the problem seems fixed.
Even removing completely the version specification would work:
gem "highcharts-rails"
getting the project to use the latest version.
I'm going to make a pull request to update the readme.
I've managed to create a chart in my Rails app using Chart.js, however for some reason, the graph doesn't display when the view loads for the first time. If I refresh the page, it displays correctly and I can't work out why. Any suggestions?
statement.html.erb:
....
<div class="col-lg-12 col-md-12 col-sm-12 col-xs-12" style="height:350px">
<canvas id="canvas"></canvas>
</div>
<script type="text/javascript">
var data = [
{
value: gon.creditTotal,
color:"#F7464A",
highlight: "#FF5A5E",
label: "Red"
},
{
value: gon.assetTotal ,
color: "#46BFBD",
highlight: "#5AD3D1",
label: "Green"
}
];
var ctx = document.getElementById("canvas").getContext("2d");
var myChart = new Chart(ctx).Pie(data);
</script>
note: I've tried wrapping the javascript inside the following but I still get the same issue:
window.onload = function(){
***here***
}
application.js:
//= require jquery
//= require bootstrap
//= require jquery_ujs
//= require jquery.ui.all
//= require Chart
//= require turbolinks
//= require jquery.turbolinks
//= require_tree .
Gemfile:
gem 'rails', '4.2.2'
gem 'bootstrap-sass', '3.2.0.0'
gem 'sass-rails', '5.0.2'
gem 'uglifier', '2.5.3'
gem 'coffee-rails', '4.1.0'
gem 'jquery-rails', '4.0.3'
gem 'jquery-ui-rails', '~> 4.2.1'
gem 'turbolinks', '2.3.0'
gem 'jquery-turbolinks'
gem 'jbuilder', '2.2.3'
gem 'sdoc', '0.4.0', group: :doc
gem 'chart-js-rails'
gem 'gon'
this is how I got working my chart.js with turbolinks
var ready = function() {
$.ajax({
url: "myurl.json",
type: "get",
async: true,
datatype : 'string'
}).done (function (data) {
var years = [];
var obstaravania = [];
var trzby = [];
var zisk = [];
var obstarcolor=[];
var trzbycolor=[];
var ziskcolor=[];
for(var i in data) {
years.push(data[i].year);
obstaravania.push(data[i].obstaravanie);
trzby.push(data[i].trzby);
zisk.push(data[i].zisk);
obstarcolor.push('#c0392b');
trzbycolor.push('#337ab7');
ziskcolor.push('#27ae60');
}
var chartdata = {
labels: years,
datasets : [
{
label: 'Obstarávania',
backgroundColor: obstarcolor,
labelColor: [ '#c0392b'],
data: obstaravania
},
{
label: 'Tržby',
backgroundColor:trzbycolor,
labelColor: [ '#337ab7'],
data: trzby
},
{
label: 'Zisk',
backgroundColor:ziskcolor,
labelColor: [ '#27ae60'],
data: zisk
}
]
};
var barOptions = {
responsive: true
};
var ctx2 = $("#mychart");
var newchart = new Chart(ctx2, {type: 'bar', data: chartdata, options:barOptions});
});
//});
};
$(".contractors.showcontractor").ready(ready);
document.addEventListener('turbolinks:before-cache', function() {
if ($('#mychart').width >1) {newchart.destroy() ;}
});
$(".contractors.showcontractor").on('turbolinks:ready', ready);
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.
I am using highcharts to generate graphical data pulled from a database.
I am having trouble using the exporting module. I have included the exporting property:
exporting{
enabled:true
}
but the buttons do not appear...
I have also linked the exporting.js to the file too...no buttons appear..
Has anyone else had this issue?
EDIT:
Here is the code:
$.ajax({
type:"POST",
url: "retrievechartdata.php",
data: {questionId:qId, questionIdTwo:qIdTwo, title:title, titleTwo:titleTwo, from:from, to:to},
dataType: "json",
success: function(data) {
//$("#response").html("<div class='successMessage'>"+ data.valuesTwo +"</div>");
var maxY = parseInt(data.max) + 1;
var minY = parseInt(data.min);
if(minY > 0){
minY = 0;
}else{
minY -= 1;
}
var cdata = new Array();
cdata= data.values.split(',');
for(var i=0;i<cdata.length;i++)
{
cdata[i]= parseInt(cdata[i]);
}
var leg = false;
var title = data.questionTitle;
if(data.valuesTwo != "FALSE"){
leg = true;
title += " & "+data.questionTitleTwo;
var cdataTwo = new Array();
cdataTwo = data.valuesTwo.split(',');
for(var i=0;i<cdataTwo.length;i++)
{
cdataTwo[i]= parseInt(cdataTwo[i]);
}
}
chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
zoomType: 'x',
spacingRight: 20
},
credits: {
enabled: false
},
title: {
text: title
},
subtitle: {
text: document.ontouchstart === undefined ?
'Click and drag in the plot area to zoom in' :
'Drag your finger over the plot to zoom in'
},
xAxis: {
type: 'datetime',
maxZoom: 14 * 24 * 3600000, // fourteen days
lineWidth: 1,
lineColor: '#999999',
title: {
text: 'Date'
}
},
yAxis: {
title: {
text: data.questionTitle
},
labels: {
y: 2
},
lineWidth: 1,
lineColor: '#999999',
gridLineWidth: 1,
gridLineColor: '#eaeaea',
min: minY,
max: maxY,
startOnTick: false,
showFirstLabel: false
},
tooltip: {
shared: true
},
legend: {
enabled: leg
},
plotOptions: {
area: {
Color: {
linearGradient: [0, 0, 0, 600],
stops: [
[0, 'rgb(69, 114, 167)'],
[1, 'rgba(2,0,0,0)']
]
},
lineWidth: 1,
marker: {
enabled: false,
states: {
hover: {
enabled: true,
radius: 5
}
}
},
shadow: false,
states: {
hover: {
lineWidth: 1
}
}
}
},
series: [{
type: 'spline',
name: data.questionTitle,
pointInterval: 24 * 3600 * 1000,
pointStart: Date.UTC(data.year, data.month, data.day),
data: cdata,
lineColor: '#f6a828',
color: '#418ed6'
},
{
type: 'spline',
name: data.questionTitleTwo,
pointInterval: 24 * 3600 * 1000,
pointStart: Date.UTC(data.year, data.month, data.day),
data: cdataTwo,
lineColor: '#808080',
color: '#ff0000'
}],
exporting: {
enabled: true
}
})
Which version of Highcharts you are using? Which version of jQuery?
Currently is the v2.1.6, I recommend you use the latest release because they are continuously fixing bugs, adding new functionality, etc.
Prior to v2.0 there is no support to the exporting feature
The only things you need to do in order to bring the exporting module working are:
1- First: Add the js script after the highcharts script, like this:
...
<script type="text/javascript" src="../js/highcharts.js"></script>
<!-- 1b) Optional: the exporting module -->
<script type="text/javascript" src="../js/modules/exporting.js"></script>
...
The exporting module is enabled by default, so there is no need to have the code you posted, so you can remove it:
exporting{
enabled:true
}
2- Second: Be sure to publish the exporting-server/index.php file correctly.
Here you have what the official documentation reads about the exporting module installation:
Exporting module
From version 2.0 an exporting module is available for Highcharts, which allows users to download images or PDF's of your charts. This module consists of an extra JavaScript file, exporting.js, and a web service or server module written in PHP. Highslide Software offers the exporting web service free of charge. If you include the exporting module in your charts, two buttons will appear in the upper right. One button prints the chart, which is done on the client side only. The other button handles exporting. By default, an SVG representation of the chart is sent by POST to http://export.highcharts.com, where it is converted using Apache's Batik converter to PDF, PNG or JPEG.
See the navigation and exporting reference items for a full documentation for the options available. Also see under "Methods and Properties" in the reference for members releated to exporting.
Here you can see the configuration options regarding the exporting module: http://www.highcharts.com/ref/#exporting
Hope it helps you.
Make sure the script tag has
type="text/javascript"