2

I have a button that links to a method, let's call it "method", inside the UserController that looks something like this:

def method
  ***do stuff***
  @my_variable = value dependent on the do stuff part
end

Is there any way to access the variable in my javascript when it is done being computed (basically, when it's defined)?

1
  • You might want to checkout the Gon gem: github.com/gazay/gon Commented Sep 4, 2015 at 22:13

2 Answers 2

1

in your erb file

<%= javascript_tag do %>
  window.MyVariable = '<%= @my_variable %>';
<% end %>

railscast http://railscasts.com/episodes/324-passing-data-to-javascript?view=asciicast

Sign up to request clarification or add additional context in comments.

1 Comment

window.MyVariable = <%= @my_variable.to_json %>;
0

If you don't want to use window. solution, here's a different idea to try.

This is what I do in my show.html.erb to pass a reverse geocoded address to map the point in a js function that uses google map API.

<!-- Must be set to pass instance vars to javascript -->
<%= javascript_tag "var js_marker_lat = #{@location.latitude.to_json};" %>
<%= javascript_tag "var js_marker_lng = #{@location.longitude.to_json};" %>

In the javascript function, you use the vars as usual.

var latlng = new google.maps.LatLng(js_marker_lat, js_marker_lng);

In the controller, javascript_tag helper is not available, so you may be limited to to using the html.erb files for js vars stuff. Please let me know how it goes.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.