-1

I want to use javascript variable inside ruby code. I tried with the following code but its not working.

 <script>
 var total=100
 <%@final_amount + = total%>
 </script>

It's throwing error because total is a java script variable. Please help me to solve this problem. Thanks in advance.

5
  • 3
    You need to understand how the client-server model works first. Ruby is server-side, JS is client-side. Ruby is executed before JavaScript. Commented Apr 30, 2014 at 4:51
  • @elclanrs so can't we do that? Commented Apr 30, 2014 at 4:52
  • Not the way you think. You can generate JavaScript in Ruby. You can communicate between the client and server using AJAX and JSON. The server and the client are isolated. Commented Apr 30, 2014 at 4:55
  • how to do that? please post as an answer. @elclanrs Commented Apr 30, 2014 at 4:56
  • Before downvoting put the reason as comment. Commented Apr 30, 2014 at 5:08

1 Answer 1

0

It's important for you to understand that your Ruby stuff is happening on the server-side and the Javascript is for the client-side. I'm not sure why you would do that in a script. I imagine you could just do that outright in your erb file in Ruby. Note that your Javascript won't know what that means.

Ruby will run, (I'm not sure if Ruby works within the script tags or they purposely don't allow that. I imagine they purposely don't allow that, so that alone will trigger an error), but it won't know what total is. It only understands Ruby. So, when you get to the client-side, you won't have ruby anymore. You'll have the html that was compiled from that Ruby. In your script, you'll have var total = 100; but you won't have that ruby script in there. It'll have been compiled to html. This is assuming erb files even allow that within scripts, which I'm not sure they do.

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.