JavaScript with Embedded Ruby: How to Safely Assign a Ruby Value to a JavaScript Variable

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>

$(document).ready(function() {
var b = $(#foo).data('bar');
var c = "string" + b;

The other option is to render your script asynchronously with unobtrusive JavaScript in Rails.

Passing JavaScript value to Ruby in ERB

The appropriate way of achieving this is using ajax in your script.

For instance you can use coffee script and do the something like this.

ABC = ->
variable = document.getElementById('textfield').value
res = $.ajax(
url: '#{method_controller_path}'
method: 'GET'
param: variable
dataType: 'json'
success: (res) ->

At the end you will have the res object to work with.

Incase you are not using coffee or external script files. You can do this using javascript in the index.html.erb file.

Here is an example for that.

const ABC = function() {
let res;
const variable = document.getElementById('textfield').value;
return res = $.ajax({
url: '#{method_controller_path}',
method: 'GET',
data: {
param: variable
dataType: 'json',
success(res) {
return res;

Hope this helps you out. :)

Assigning ruby variable from the controller to a javascript variable

I just want to close this question, that is why I am answering my own question. Teeg told me to use Gon, which is what ended up working for me but he put in in a comment so I couldn't vote it as the answer.

assign javascript variable to ruby variable

Actually, if I understand your code (your question is not well phrased, unfortunately), the simple solution is:

1- Assign a value via server-side code:

function set_color(val1,val2)
var bkgdColorId = "<%= background_color_id %>";
var obj_color_id = bkgdColorId;

2- (Or,) Assign a value from client-side code:

function set_color(val1,val2)
/** pseudo-code **/
on-click-event: makeAjaxCallToServer(){
urlForWebService, { color: val2 }

Using some jQuery (if assigning to server from client-side event) would greatly facilitate this process.

Include a javascript variable into a ruby code in js.erb file

Thanks to the answer of @max here is the solution including a selected param and a class.

select("company", "company_id", Company.all.collect {|p| [,, { 'data-url-path'=>p.logo_url(:thumb) }] }, { selected: params["company_id"] }, { class: "select-company" })
$('#company_company_id').on('select2:select', function (e) {
var data =;
var src = $('#company_company_id select option[value="' + + '"]').data('url-path');
$(".my_img").attr("src", src);

use javascript variable inside % % in erb - Ruby on Rails

solved: The right way do to it is to use ajax:

in your page.erb

<% content_for :javascript do %>
var temp_name = $('#category').val();
url: "/YOUR_PATH/"+temp_name,
dataType: "html",
type: "GET",
success: function(data){
<% end %>

<div id="template_overview">

have a partial that populates your div

in the controller:

def display_template
render partial: '/PATH/template_overview', header: @header

and of course the routes

get 'controller/display_template/:temp_id' => 'controller#display_template'

How to call ruby value in Javascript

If you are using erb for your views:

# your_view.html.erb
document.getElementById("quoteArea").value = "<%= @random_quote.quote %>";

If you are using HAML for your views:

# your_view.html.haml
document.getElementById("quoteArea").value = "#{@random_quote.quote}";

How to pass a javascript variable into a erb code in a js view?

As far as i know there is no way to do it directly and the reason is fairly simple too, html is executed at the server side and javascript is a client side language which means its executed in your local browser, thats why if you even try to pass a variable between the two you'll have to make a request to the server,
However this problem is tackled by calling an AJAX request, this AJAX request does the same thing as sending a new request to the server however it does that without refreshing or reloading the page to it gives the users the illusion that no request was made.

a guy asks a similar question Here

and you can learn more about AJAX Here on MDN:

How do I properly put embedded ruby code in to JavaScript?

You shouldn't be putting quotes around your ERB code, otherwise it puts the results in a string instead of assigning it to stuff as a hash/JSON object. Remove them and it should work. (Also, <% should be <%=).

var stuff = <%= Representative.get('') %>;

Related Topics

Leave a reply