Passing Variable from JavaScript to Ruby on Rails

Rails 4: Passing variables to javascript

I used to do:

var my_var = <%= User.count %>
console.log(my_var)

If it is an integer this works just fine.
If, however, you want to pass objects, then use:

var my_var = JSON.parse(('<%= (@Users.count) == 0 ? "[]" : Users.first(10).to_json %>')

console.log(JSON.stringify(my_var))

Is there a way to pass javascript variable into ruby method in html.erb

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.

How to pass a variable to javascript in Rails 6 app

It's quite a common pattern in Rails applications to pass atrributes via data attributes.

In your view template you'd interpolate the user ID:

<div id="calendar" data-user-id="<%= @user.id %>">
</div>

And in your JavaScript you'd read the user ID via the dataset:

var calendarEl = document.getElementById('calendar');
var userId = calendarEl.dataset.userId;

How to pass javascript variable to rails partial view

As Alberto Juan wrote in comment, you can't use javascript variable in ruby code.
Ruby code will be interpreted before javascript and will not know what is the i.

Update: Your update will not work either as your using new_variable you get in your javascript code.

For using partial after ajax call, follow instructions in this link

Example:

items/index.html.erb

<div class="grid">
<% @categories.each do |cat| %>
<%= link_to cat.name, fetch_items_path(:cat_id => cat.id), :remote => true %>
<% end %>

<%= render partial: 'item_grid', locals: { items: @items} %>
</div>

routes.rb

get "/fetch_items" => 'items#from_category', as: 'fetch_items'

items_controller.rb

def index
@items = Item.all
@categories = Category.all
end

def from_category
@selected = Item.where(:category_id => params[:cat_id])
respond_to do |format|
format.js
end
end

views/items/from_category.js.erb

$("#items_grid").html("<%= escape_javascript(render partial: 'items_list', locals: { items: @selected } ) %>");  

Passing variable from Javascript to Ruby on Rails

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.


Related Topics



Leave a reply



Submit