0

Passing data from Ruby to Javascript is easy, for example:

<script type="text/javascript">

    function change_value(val){

      alert ("<%= @alert %>")   
      }
    }
</script>

This will sent an alert with the data stored at the alert variable in the controller.

But I don't know how it works in the opposite direction, for example, if I need to store an element id into a controllers variable:

<script type="text/javascript">

    function change_value(element){
      <% @element_id = *** element.id *** %>

      alert ("<%= @element_id %>")   
      }
    }
</script>

The real deal is up next, the code surrended by *** are supposed to be the needed javascript values (@billeable_qts is a Hash):

<script type="text/javascript">

  function change_value(product){

    <% @billeable_qts[****product.id****] = ***document.getElementById('product.id').value****  %>
    <% @billeable_qts.each do |key, value| %>
       <% alert = "Key = " + key + ", value: " + value.to_s%>
       alert ("product: <%= alert %>")
    <% end %>


  }

</script>
2
  • 1
    You can't. The javascript is running in the browser. To post those kinds of changes back to your app you'd have to do something like an AJAX request, which in turn would return your additional content to render in the page. Commented Jan 19, 2018 at 21:28
  • You asked this identical question yesterday. Commented Jan 19, 2018 at 21:31

1 Answer 1

1

As everyone has suggested, you can't do it the way you're wanting.

A simple workaround would be to create a method (or use one that's already in your controller), and then do an ajax call to the method.

For example, do an ajax call to the update method of the first product, and pass in the variables you want to update in the params:

     var value = document.getElementById('product.id').value   
     var id = 1

      $.ajax({
            url: '/products/' + id,
            type: 'POST',
            data: {
                product: {
                    value: value,
                }
            },
            success: function(result)   {
                location.reload();
            },
            error: function(err)    {
                console.log(err);
            }
        })
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.