I have this code in my view in index.html.erb
<html>
<head>
<!--Load the AJAX API-->
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
// Load the Visualization API and the piechart package.
google.load('visualization', '1.0', {'packages':['corechart']});
// Set a callback to run when the Google Visualization API is loaded.
google.setOnLoadCallback(drawChart);
// Callback that creates and populates a data table,
// instantiates the pie chart, passes in the data and
// draws it.
function drawChart() {
// Create the data table.
var data = new google.visualization.DataTable();
data.addColumn('string', 'Topping');
data.addColumn('number', 'Slices');
ActiveRecord.connect()
var accounts = Account.find({
all: true,
order: 'id DESC'
});
for (var i=0;i<accounts.length;i++)
{
document.write(accounts.a_name);
data.addRow([accounts.a_name, accounts.a_amount]);
}
// Set chart options
var options = {'title':'Accounts balance distribution',
'width':600,
'height':500};
// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
</head>
<body>
<!--Div that will hold the pie chart-->
<div id="chart_div"></div>
</body>
</html>
The Account model is not returning any value, do you know how to change the code to make it returns values
Thank you and looking forward for your feedback
/Mohamed sami
Since ERB stands for Embedded Ruby, you have to embed it :
So when you write var accounts = value, you have to embed 'value' into <%= and %> and make sure that value is some ruby that returns the appropriate string for your Javascript (the same that you would have hard-written if it wasn't dynamic).
Related
I would like to set my own ticks on the horizontal axis of a Google Chart. I included hAxis.ticks (as per the documentation) in my attempt below, but it refuses to work since the ticks are still not integers even though I specified them to be.
What am I doing wrong?
<html>
<head>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
google.charts.load('current', {'packages':['line']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn('number', 'Day');
data.addColumn('number', 'myNumber');
data.addRows([
[1,17],
[2,18],
[3,20]
]);
var options = {width: 800, height: 500, hAxis: {ticks: [1,2,3]}};
var chart = new google.charts.Line(document.getElementById('chart'));
chart.draw(data, google.charts.Line.convertOptions(options));
}
</script>
</head>
<body>
<div id="chart"></div>
</body>
</html>
ticks is not a supported option for material charts.
material --> google.charts.Line -- packages:['line']
classic --> google.visualization.LineChart -- packages:['corechart']
you would need to use a classic chart.
note: there is an option for classic charts to have a similar look...
theme: 'material'
you can find the full list of unsupported options here...
Tracking Issue for Material Chart Feature Parity
I am trying to create a line chart of changes in prices every minute. I need to be able to pull the data from my site. I can't get the chart to load if I use datetime for the x axis.
<html>
<head>
<!--Load the AJAX API-->
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
// Load the Visualization API and the piechart package.
google.charts.load('current', {'packages':['corechart']});
// Set a callback to run when the Google Visualization API is loaded.
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var jsonData = $.ajax({
url: "sampleData.json",
dataType: "json",
async: false
}).responseText;
// Create our data table out of JSON data loaded from server.
var data = new google.visualization.DataTable(jsonData);
// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, {width: 800, height: 480});
}
</script>
</head>
<body>
<!--Div that will hold the pie chart-->
<div id="chart_div"></div>
</body>
</html>
I can create a chart using the following for sampleData.json:
{
"cols": [
{"id":"","label":"X","pattern":"","type":"string"},
{"id":"","label":"Line 1","pattern":"","type":"number"},
{"id":"","label":"Line 2","pattern":"","type":"number"}
],
"rows": [
{"c":[{"v":"1","f":null},{"v":3,"f":null},{"v":4,"f":null}]},
{"c":[{"v":"2","f":null},{"v":1,"f":null},{"v":2,"f":null}]},
{"c":[{"v":"3","f":null},{"v":1,"f":null},{"v":3,"f":null}]},
{"c":[{"v":"4","f":null},{"v":1,"f":null},{"v":1,"f":null}]},
{"c":[{"v":"5","f":null},{"v":2,"f":null},{"v":5,"f":null}]}
]
}
But when I try to change x to a datetime, it won't load.
{
"cols": [
{"id":"","label":"X","pattern":"","type":"datetime"},
{"id":"","label":"Line 1","pattern":"","type":"number"},
{"id":"","label":"Line 2","pattern":"","type":"number"}
],
"rows": [
{"c":[{"v":new Date(2017,0,1,12,1),"f":null},{"v":3,"f":null},{"v":4,"f":null}]},
{"c":[{"v":new Date(2017,0,1,12,2),"f":null},{"v":1,"f":null},{"v":2,"f":null}]},
{"c":[{"v":new Date(2017,0,1,12,3),"f":null},{"v":1,"f":null},{"v":3,"f":null}]},
{"c":[{"v":new Date(2017,0,1,12,4),"f":null},{"v":1,"f":null},{"v":1,"f":null}]},
{"c":[{"v":new Date(2017,0,1,12,5),"f":null},{"v":2,"f":null},{"v":5,"f":null}]}
]
}
You should remove the new keyword when working with JSON.
From google charts:
https://developers.google.com/chart/interactive/docs/datesandtimes
"When serializing data using the JavaScript DataTable object literal notation to build your DataTable, the new Date() constructor cannot be used. Instead, Google Charts provides a Date string representation that allows your date or datetime to be serialized and parsed properly when creating a DataTable. This Date string format simply drops the new keyword and wraps the remaining expression in quotation marks:
"Date(Year, Month, Day, Hours, Minutes, Seconds, Milliseconds)"
I'm trying to incorporate Google Charts into a javascript object oriented web app. After the app is loaded - the idea is that the user clicks a certain button which builds/displays a certain chart.
I suspect that I have a scope problem. Firefox/Firebug throws "InvalidCharacterError: String contains an invalid character" which isn't very helpful.
Below is a snippet of what I'm trying to do. Perhaps someone can point out some obvious problem with my attempt?
Thanks in advance for your help.
<html>
<head>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script language="JavaScript" type="text/javascript">
google.load('visualization', '1.0', {'packages':['corechart']});
</script>
</head>
<body>
<div id="googlecharttest"></div>
</body>
</html>
BUTTON CLICK EVENT -> OBJchart.build_googlechart();
------------------
Javascript Snippet
------------------
OBJchart = new Fchart();
Fchart = function() { return {
...
build_googlechart : function()
{
this.drawChart();
// also tried this - with the same result.
// google.load('visualization', '1.0', {'packages':['corechart'], 'callback': this.drawChart});
},
drawChart : function()
{
var data = new google.visualization.DataTable();
data.addColumn('string','Topping');
data.addColumn('number','Slices');
data.addRows([['Mushrooms', 3],['Onions', 1],['Olives', 1],['Zucchini', 1],['Pepperoni', 2]]);
var options = {'title':'How Much Pizza I Ate Last Night','width':400,'height':400};
var chart = new google.visualization.LineChart(document.getElementById('googlecharttest'));
chart.draw(data,options);
},
...
};};
I am trying to draw a bar graph using the values returned from server using jQuery. I use the following code,
I try to draw graph using the values in the variable data_list, the issue is the graph draws first with empty values the I got values from server.
I am a newbie to Javascript and jQuery. Thanks in advance.
<html>
<head>
<title>the title</title>
<script src="//code.jquery.com/jquery-1.9.1.js"></script>
<link rel="stylesheet" href="//code.jquery.com/ui/1.10.4/themes/smoothness/jquery-ui.css">
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script src="//code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
<script>
$(function() {
$( "#datepicker1" ).datepicker();
$( "#datepicker2" ).datepicker();
});
</script>
<script type="text/javascript" language="javascript">
var data_list
$(document).ready(function() {
$.get('/api/', function(data) {
data_list = data;
alert(data_list); // alert work second
});
});
alert('test') // first this alert work
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable(data_list);
var options = {
title: 'Company Performance',
hAxis: {title: 'Year', titleTextStyle: {color: 'red'}}
};
var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
</head>
<body>
<form>
<p>Date1: <input type="text" id="datepicker1"></p>
<p>Date2: <input type="text" id="datepicker2"></p>
</form>
<div id="chart_div" style="width: 900px; height: 500px;"></div>
</body>
</html>
There are two parts in yout JS code. The first is loading the chart data from your API with an AJAX request. The second starts the chart library and attach the data in this line:
var data = google.visualization.arrayToDataTable(data_list);
The problem is the ajax request is asynchronous and the data is not loaded yet when you attach that data. The data_list var will be avaliable when the AJAX request finishes and not when the page is loaded. In other words, you must separated the initialization of the chart and the data attach to it, or simply: init the graph, load the data and set it to the chart when the AJAX request is done. A simple example with your code (not tested) could be:
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
$(document).ready(function() {
$.get('/api/', function(data) {
data_list = data;
var data = google.visualization.arrayToDataTable(data_list);
var options = {
title: 'Company Performance',
hAxis: {title: 'Year', titleTextStyle: {color: 'red'}}
};
var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
chart.draw(data, options);
});
});
}
Remember this code is not tested, it ilustrates the idea of the correct initialization:
- Load Google Chart Library
- Load the data
- When the data is loaded, init the concrete chart
The asynchronous load adds some complexity to the code, but are the base of programming in JavaScript with AJAX and DOM events. Another option, more readable and simple, is to use jquery deferred objects and promises. More on deferred and promises:
- http://api.jquery.com/category/deferred-object/
- http://www.html5rocks.com/en/tutorials/es6/promises/?redirect_from_locale=es
I'm trying to loop through a list of objects (some measurements data) using JSTL forEach tag in javascript and display the data by using Google Charts API. The code is showing as following. But looks something wrong. As I double checked, the data in the list of measurements objects works fine to pass to html in ${listOfMeasurements}, ${measurements.measTime}, ${measurements.measS1raw} and ${measurements.measS2raw}. But in the javascript block, the forEach code is not working to execute data.addRow() as expected. My guess is, I'm not using forEach correctly in my javascript code, so data.addRow() was not executed as expected. How can I fix it?
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Date');
data.addColumn('number', 'measurement1');
data.addColumn('number', 'measurement2');
<c:forEach items="${listOfMeasurements}" var="measurements">
"data.addRow("
+"${measurements.measTime}"+","
+"${measurements.measS1raw}"+","
+"${measurements.measS2raw}"+");"
;
</c:forEach>
var options = {
title: 'Measurements'
};
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
Try it like this
<c:forEach items="${listOfMeasurements}" var="measurements">
data.addRow(${measurements.measTime},${measurements.measS1raw},${measurements.measS2raw});
</c:forEach>
Otherwise you will obtain wrong code in your script, for example:
"data.addRow("+"measTimeValue-1"+","+"measS1raw-1"+","+"measS2raw-1"");";
"data.addRow("+"measTimeValue-2"+","+"measS1raw-2"+","+"measS2raw-2"");";
"data.addRow("+"measTimeValue-3"+","+"measS1raw-3"+","+"measS2raw-3"");";
...and that's incorrect javascript.
The problem with mixing JSP tags and Javascript is that they occur in two differents phases.
JSP Rendering comes first, so all html, css and javascript code is just another string. So after the JSP Rendering finishes, you have just HTML.
You may want to read this blog entry from BalusC about this topic.
This could be alternate solution....
function drawBasic() {
var data = google.visualization.arrayToDataTable([
['Date', 'measurement1','measurement2']
<c:forEach var="measurements" items="${listOfMeasurements}">
,[${measurements.measTime},${measurements.measS1raw},${measurements.measS2raw}]
</c:forEach>
]);
var options = {
title: 'Change title Acoordingly',
chartArea: {width: '50%'},
hAxis: {
title: 'Change title Acoordingly',
minValue: 0
},
vAxis: {
title: 'Change title Acoordingly'
}
};
var chart = new google.visualization.BarChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
<body><div id="chart_div"></div></body>