5

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.

2

4 Answers 4

1

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.

Sign up to request clarification or add additional context in comments.

Comments

1

There is a nice gem gon for performing this job. Using this gem you can do this:

Inside controller:

gon.push(variable_name: 1)

Inside your js files you can retrieve this variable:

gon.variable_name 

It's working for :js or :coffee files.

1 Comment

gon passes rails variables into js. But the OP wants to pass js variable into ruby.
0

Ruby code is executed at the server while Javascript is executed by the client's browser.

Ruby code marked by <%= %> is executed at the server and then delivered to the client, where Javascript code will be executed. That is why the first snippet does not work while the second one does: in the second snippet, <% @b = 1 %> gets evaluated before sending out HTML to the requester.

With that said, there is a way to do what you want: use Ajax to pass the Javascript variable to the server, execute whatever you need and send back an answer to the client.

Comments

0

You need to describe your process flow better.

Case 1: The value of the variable is determined by user action. Then make an ajax call to rails object method to get the computed value to js.

Case 2: The value of the variable is determined by the app(server side). Then you can do:

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

Same value will be available to JS and server method. But this is not a clean approach. View should not set the value.

And also, keep js in asset pipeline as suggested by @jeffD23

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.