urco
urco

Reputation: 189

Passing variable from Javascript to Ruby on Rails

In rails you can do this:

<% name = @user.name %>
<script>
    var name = <%= name%>;
    alert(name);
    //prints the name of the user
</script>

You can do this in reverse, like this

<% name = @user.name %>
<script>
    var name = "John";
    <% name %> = name;
</script>

<% @user.name = name %>

<%= name %>
<!-- prints the name of the user, in this case "John" -->

Obviously this doesn't work, but for the purpose of an example

The point is, can you pass the value of a javascript variable to a ruby variable in rails

Upvotes: 4

Views: 3343

Answers (1)

MrYoshiji
MrYoshiji

Reputation: 54902

No, you can't pass a variable directly from javascript to rails:

  • Ruby on Rails' code is executed on the server-side, to generate the page (with HTML, CSS, and Javascript).
  • Javascript's code is executed on the client-side, by the browser.

The only way to communicate client -> server is to use a request. You can use AJAX (Asynchronous Javascript And XML) to send a request from the client to the server without reloading the page.


You have to understand some concepts about code on the server vs client side. The process of "displaying a page from a website":

  • (Client-side) The user sends an HTTP request to the server for a page, sending the location of the page, example: http://myapp.com/users
  • (Server-side) The server gets the request, find the proper controller/action following the defined routes
  • (Server-side) The server generates the page in HTML/CSS/Javascript to send back to the user. It generates the HTML via the views & partials, executes the ruby code of these pages.
  • (Server-side) Once the page is rendered, the server sends the HTTP response with the HTML/CSS/Javascript in the body.
  • (Client-side) The client's browser receives the response of the server and reads the body composed of HTML/CSS/Javascript (mostly). The browser parses and renders the HTML/CSS, and execute the javascript.

Upvotes: 5

Related Questions