Reputation: 1797
I have this javascript code, from google charts api right in the bottom of my view :
<div id='visualization'></div>
...
<script type="text/javascript">
function drawVisualization() {
// Create and populate the data table.
var data = google.visualization.arrayToDataTable(<%=raw @pie_gender %>)
// Create and draw the visualization.
new google.visualization.PieChart(document.getElementById('visualization')).
draw(data, {title:"Men and Women"});
}
google.setOnLoadCallback(drawVisualization);
</script>
I've tried to put this js code in my assets folder under a .js file, and include it in my headers, as well as replacing <%=raw @pie_gender %>
with this.getAttribute('data-message')
and putting my div as ', but then i get a javascript error "getAttribute" does not exist for object window
I have also tried to pass my array as an input argument like : onload="drawVisualization(<%=raw @pie_gender %>)
, but then I get "Error: Not an array"
What might I be doing wrong ?
EDIT
@pie_gender = [['Gender', 'Occurences']['M', 10]['F', 5]]
Based on example from google
EDIT 2 If i print the json output
<% logger.debug "Pie Gender : #{@pie_gender.to_json}" %>
<div id="visualization" onload="drawVisualization(<%= @pie_gender.to_json %>)" > </div>
,it seems just fine :
Pie Gender : [["Gender","Receipts"],["",25000],["F",8658]]
but it seems that something happens while sending this as an argument to my js function, because it still says that message is not an array :
function drawVisualization(message) {
// Create and populate the data table.
var data = google.visualization.arrayToDataTable(message);
// Create and draw the visualization.
new google.visualization.PieChart(document.getElementById('visualization')).
draw(data, {title:"Men and Women"});
}
google.setOnLoadCallback(drawVisualization);
Upvotes: 0
Views: 287
Reputation: 1797
To workaround this, I inserted my javascript code in a partial
_googlescript.html.erb
<script type="text/javascript">
function drawVisualization() {
// Create and populate the data table.
var data = google.visualization.arrayToDataTable(<%=raw data_array %>)
// Create and draw the visualization.
new google.visualization.PieChart(document.getElementById('visualization')).
draw(data, {title:"Men and Women"});
}
google.setOnLoadCallback(drawVisualization);
</script>
in my view I rendered the partial in the bottom of the page, and removed the onload, which just seemed not to be doing a thing... :
<div id="visualization" > </div>
...
<%= render partial: 'shared/googlescript', locals: {data_array:@pie_gender} %>
Now i can see the chart again...but i still feel there is a better answer to my question.
Upvotes: 1