0

Passing a variable from Rails 6 to Javascript is working:

<% @hi = "Hi!" %>

<script type="text/javascript">
  var ac = '<%= @hi %>';
  alert(ac);
</script>

How can I pass a variable from Javascript to Rails 6?

1 Answer 1

1

You can't get data from Javascript to Rails in such a simple way as you can in the other direction.

You don't specify your exact use-case here, but you should bear in mind that Javascript potentially doesn't run until the page is loaded, meaning the main server request is over by then, so the browser can't pass information back to the server without a new request.

If you can rearchitect to avoid needing to send data from Javascript to Rails, that would be the easiest solution.

If you absolutely need to pass information pass to Rails (for example because it's user input), you will need to start another request, such as an AJAX request in Javascript, or a form submit (maybe with a hidden field).

When doing so, you should bear in mind security issues here, i.e. you can't trust any information that comes from Javascript/the user's browser, as there's no guarantee a hacker won't run entirely different Javascript. This is one major reason you don't send back unnecessary data.

Also note that you should use the j helper (aka escape_javascript) if you want to reliably put Rails variables into inline Javascript.

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

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.