Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails: pass data to javascript [duplicate]

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

like image 702
Tom Avatar asked Aug 10 '13 13:08

Tom


2 Answers

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.

like image 196
Powers Avatar answered Nov 18 '22 02:11

Powers


I do something similar to, but simpler than gon. I have the following in my ApplicationController.

def javascript_variables(variables)
  @javascript_variables ||= {}
  @javascript_variables.merge!(variables)
end

Within a controller action I can then do something like

def some_action
  javascript_variables(user: current_user)
end

In my ApplicationHelper I have something like this

def javascript_variables(variables = nil)
  @javascript_variables ||= {}
  @javascript_variables.merge!(variables) and return if !variables.nil?

  output  = ''
  padding = @javascript_variables.keys.group_by(&:size).max.first

  @javascript_variables.each do |variable, value|
    output << "#{variable.to_s.ljust(padding)} = #{value.to_json},\n          "
  end

  raw "var " + output.strip.html_safe.gsub(/\,\Z/m, ';')
end

and finally in my layout's <head> I have

<script>
  <%= javascript_variables %>
</script>

This gives me something like this (from a real example in my application)

<script>
  var pageModule        = "site/index",
      isCustomer        = false,
      utype             = "normal",
      isAnonymous       = true,
      keyboardShortcuts = false,
      pubnub            = null,
      requestToken      = "3zj974w074ftria3j";
</script>
like image 33
deefour Avatar answered Nov 18 '22 03:11

deefour