Pass data from Controller to Javascript in Rails -


i trying use google charts api following example google charts quick start

as see data created in js as:

data.addcolumn('string', 'topping');         data.addcolumn('number', 'slices');         data.addrows([           ['mushrooms', 3],           ['onions', 1],           ['olives', 1],           ['zucchini', 1],           ['pepperoni', 2]         ]); 

my question is:

if in controller data... how can pass javascript of template file? have example js hooked in head of index.html.erb file.

you need create ruby variable in controller action hold values , generate javascript in view using them values using <%= %> tags.

example: @values name value collection.

data.addcolumn('string', 'topping'); data.addcolumn('number', 'slices'); data.addrows([     <% @values.each |v| %>         ['<%= v.name %>', <%= v.value %>],     <% end %>     ]); 

example using js function.

index.js:

var values;  function initpage(valuesfromview) {     values = valuesfromview; }  function initdata() {     data.addcolumn('string', 'topping');     data.addcolumn('number', 'slices');     data.addrows(values); } 

index.html.erb: note i'm using jquery call initpage when page loads, if you're not using jquery initpage call in onload of body tag or similar.

<script>     $(document).ready(function() {         initpage([            <% @values.each |v| %>                ['<%= v.name %>', <%= v.value %>],            <% end %>         ]);     }); </script> 

Comments

Popular posts from this blog

jquery - Invalid Assignment Left-Hand Side -

java - Play! framework 2.0: How to display multiple image? -

gmail - Is there any documentation for read-only access to the Google Contacts API? -