0

Is there a way to pass a Javascript variable to a Rails path?

For example, I have in my html.erb file:

<script>
for (i=1, i< numSteps, i++){
   var step = i
   td.innerHTML = <%= project_step_path(@project, step) %>
}
</script>

But this doesn't work since step is a Javascript variable.

2 Answers 2

3

In this case, the Ruby will run on the server. It will generate some text. That text is sent to the browser. The browser will parse it as HTML and JS.

You can't do bi-directional synchronous communication in a single HTTP request/response.

So no.

Each time you want to send data from client side JavaScript to server side Ruby you need to issue a new HTTP request.

Issuing such a request can be done by:

  • setting location
  • submitting a form
  • using the XMLHttpRequest object
  • generating an element (such as a script or an image) that can have an external src
  • and a host of other methods.
Sign up to request clarification or add additional context in comments.

Comments

2
  • JavaScript runs on the browser
  • Rails runs on the server.

They can not run together.

2 Comments

thanks for your response! do you have any suggestions for how I might accomplish what I want to do instead?
Just do the loop on the server side? Unless it was just an example and you're trying to do something different..

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.