I have a form for editing profiles. Rails automatically generates the form id as 'edit_profile_##' where ## is the profile id of the current user(instance variable-@profile_id). I need to use this form id for my javascript functions. Is there a way to get the current user's profile id inside js? Or is there a way I can override the automatic id generation by rails?
3 Answers
you have to send that using 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)
}
2 Comments
Sathya
ok thanks. so thats the only way then? i was trying to see if there was a way without passing it in a function call. coz my js function (see below-submitProfileForm) is actually an event handler which needs to be called only when the form is submitted Event.observe('window','load',function(){ $('edit_profile_##').observe('submit',submitProfileForm); });
Salil
yes that is the only way you can access instance variable in .js file
Are you using normal *.html.erb views?
Can't you do something like :
<script type="text/javascript">
user_id = <%= @profile_id %>;
</script>
?
2 Comments
Sathya
yes i do use html.erb views. So u mean to say i can include this in my html.erb file? but how do i access user_id inside my .js file?
Francisco Soto
I have no idea how you have your js files. But you can create methods and then pass the parameter around, or create a global variable (like in my example, though I really would not recommend that).
lets say you have @user = {'name'=>'steve'} in the controller
now your html page can render <p> <%=@user['name']%> </p>
now lets say you want to be able to access @user in your .js file; add thisThing & data-url to 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 (its in string)