OK to set a Rails variable inside javascript function?

Is there something wrong with setting a Rails variable inside a javascript function? I could not answer a specific question and just wanted to make sure that there were no catches or flaws that I did not know about. I am really confused about how this works at all - if javascript is executed on the client side, I would not assume that Rails will respond to changing a variable in the view after rendering the view.?

(example) I have several functions that call the same form, and I need to know which function is called forms to perform certain tasks in the controller method (the session in this case is a cookie, but I also tried the local Rails variable, and it also works).

<script type="text/javascript">

    $('.open_new_item_form' ).click(function(){
     alert('<%= session[:item_form_type]%>');
        <% session[:item_form_type] = "from_new_item_click" %>
     alert('<%= session[:item_form_type]%>');
        var url = $(this).attr("href");
        $.ajax({
etc...

The warnings seem to work well. It will warn about the current value, and then about the new value from_new_item after dialing.

Thanks - just make sure

+3
source share
3 answers

Part of the rendering process for rails is the evaluation of all erb code in this view. After the code evaluation is completed, the rails will then display the file (be it javascript, html, etc.).

So, when you say that you were surprised to see that the rails can react to a variable change, this is because the view was not really made at that moment ... it was in the process of rendering.

+1
source

erb ; javascript, javascript :

    <% session[:item_form_type] = "from_new_item_click" %>

javascript if, false, :

    if(0){<% session[:item_form_type] = "from_new_item_click" %>;}

( pidgin -javascript, , .)

+5

, , . , , Ruby , Javascript, . ; , :

alert('<%= session[:item_form_type]%>');

- :

alert('from_new_item_click');

If you really want to change your RoR code on the server side when the user takes an action, you need to use AJAX. Basically, AJAX allows your Javascript code to send GET / POST to a URL. So in your .click event handler, you can push the URL that triggers an action that changes any session variables you want.

(Sorry, if you already know everything about AJAX, I suspect you might not have asked your question.)

+1
source

All Articles