How to access instance variable inside Javascript function in Ruby on Rails application?

I have a form for editing profiles. Rails automatically generates the form identifier as "edit_profile _ ##", where ## is the profile identifier of the current user (the instance variable is @profile_id). I need to use this form id for my javascript functions. Is there a way to get the current user profile id inside js? Or is there a way I can override auto-generate id using rails?

+4
source share
3 answers

you need to send this using a function parameter

.html.erb

<script type="text/javascript"> var user_id = <%= @profile_id %>; // for integer var user_name = '<%= @profile_name %>'; // for string abc(user_id)// this is your function in .js file </script> 

.js

  function abc(id){ alert(""+id) } 
+7
source

Do you use regular * .html.erb views?

You cannot do something like:

 <script type="text/javascript"> user_id = <%= @profile_id %>; </script> 

?

+1
source

let's say you have @user = {'name'=>'steve'} in the controller

now your html page can display <p> <% =@user ['name']%> </p>

now lets say that you want to have access to @user in your .js file; add thisThing and the url for your tag <p id="thisThing" data-url="<% =@user %>" > <% =@user ['name']%> </p>

in your .js file var userInfo = $('#thisThing').data('url')

now you got userInfo in your .js (in line)

0
source

Source: https://habr.com/ru/post/1314395/


All Articles