Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to access javascript variable in rails view

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

like image 563
Prashant Avatar asked Sep 15 '25 12:09

Prashant


2 Answers

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>
like image 66
alex.zherdev Avatar answered Sep 17 '25 04:09

alex.zherdev


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.

like image 34
liviu.r2 Avatar answered Sep 17 '25 05:09

liviu.r2