Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to pass javascript variable into ruby method in html.erb

I'm trying to pass a variable into a method. Here is an example:

<script>
  var b = 1
  var c = "string" + "<%= method.a(b).to_s%>"
</script>

which doesn't work.

This works:

<% @b = 1%>
<script>
  var c = "string" + "<%= method.a(@b).to_s%>"
</script>

Any ideas would be appreciated.

like image 836
Richardlonesteen Avatar asked Oct 30 '22 18:10

Richardlonesteen


1 Answers

You can't evaluate a JavaScript variable inside your Ruby method. Also, your current script has to be outside the asset pipeline, which is usually a bad practice.

One simple solution is to pass the variable as a data attribute. You would run your method, then pass the result with jQuery after the DOM has loaded. This allows you to keep JavaScript in the asset pipeline and pass it data evaluated by Ruby server-side.

Note: @b should be defined on your controller:

<div id="foo" data-bar="<%= method.a(@b).to_s %>"></div>

<script>
  $(document).ready(function() {
    var b = $(#foo).data('bar');
    var c = "string" + b;
  });
</script>

The other option is to render your script asynchronously with unobtrusive JavaScript in Rails.

like image 114
JeffD23 Avatar answered Nov 11 '22 04:11

JeffD23