Rails: pass data to javascript

javascript, ruby-on-rails

Solution

I wrote an article on how to pass Ruby objects to the client. Ryan Bates also has an excellent RailsCast on passing data to JS.

Add a div to your view that corresponds to your the PagesControlle#home action that will not be visible when you load the page but will contain the data stored in the Ruby objects:

# views/pages_controllers/home.html.erb
<%= content_tag :div, class: "temp_information", data: {temp: @temp} do %>
<% end %>

Load the page with this div included and view the page source. You can see your Ruby objects stored in the `.temp_information` div. Open up the JavaScript console to access the Ruby objects as JavaScript objects:

$('.temp_information').data('temp')

You do not need to add your JS to a JS partial, you can also use the asset pipeline.

Problem

i'm new in Rails and in a controller i have: ``` class PagesController < ApplicationController def home @temp = "Hello" end end ``` I have read that i must put the javascript code in application.js (tell me if true) and i have: ``` window.onload=function(){alert("<%= j @temp %>")} ``` Obviously that alert print the string "<%= j @temp %>" How can i pass the variable @temp to the javascript so that the alert can print Hello? Thanks

Original source

Related problems