4

Is there any way to access javasript variable inside the rails view. I just set some value of javascript variable and want to access it in rails view.

Thanks

4 Answers 4

8

You have to understand that ruby code in your views gets executed on the server - before any javascript on the page gets a change to be executed.

That's why you cannot do stuff like this:

<script>
  var js_var = 1;
</script>

<%= get_value_of_js_var_somehow %>

The other way round it works:

<script>
  var js_var = <% generate_value_with_ruby %>;
  do_something_in_javascript_with_js_var();
</script>
Sign up to request clarification or add additional context in comments.

1 Comment

and here is a very simple example how to "do_something_in_javascript" - stackoverflow.com/questions/6835512/…
4

You can pass a javascript variable to rails using AJAX. For example if you want to pass the id for an user to a method in a rails controller from javascript you can execute the following code:

<script>
  var id = 1;
  <%= remote_function :url => {:controller=>'controller_name', :action=>'method_name'}, :with => "'user_id=' + id" %>
</script>

You will receive the variable through a POST request, as a parameter. You can access it using params[:user_id].

def method_name
  if params[:user_id].exists?
    u = User.where('id = ?', params[:user_id]).first
  end
  puts u.path
end

Hope I've answered your question.

Comments

0

If you have this Javascript variable in a higher piece of javascript (per se: the application.js), then you can always just reference it in the view.

#application.js
var someVar = "Hello World";

Then in your view (executed on the client), you could to...

<script type='text/javascript'>
  alert(someVar);
</script>

I think we need more specific ellaboration if one of these three posts doesn't answer your question.

Comments

-1

Suppose we are having script as follows

<script type="text/javascript">
  var a="some value";
  document.getElementById('tagid').innerHTML='<%= tag(:div,content_tag(:p,' " +a+ " '), :id=>' " +a+ " ', name=>"somename") %>';
</script>

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.