How to Use JavaScript Variables in Ruby

How to use javascript variables in ruby

One method that is probably the easiest that I know of, and a conventional way to go about handling this, is to perform an Ajax request. JavaScript is client-side and Ruby is server-side usually.

You can create a route in your routes file, and then, in the corresponding controller, create the action which responds with the JavaScript instead of HTML. In that JavaScript file, you can change or modify things on the page and have access to the variable you changed, re-render parts of the page, and so on. I'll use jQuery here, because it's a bit cleaner.

In your routes file:

post 'some_controller/make_a_change', to: 'some_controller#make_a_change'

Then, in the function you have defined above:

$.ajax({
url:'/some_controller/make_a_change', //Defined in your routes file
data:(
'special_id=' + $('#special_id').val() + '&' +
'target_area_id=' + $('#target_area_id').val()
)
})

In SomeController.rb you can access your JavaScript values via params:

def make_a_change
some_special_id = params[:special_id]
taid = params[:target_area_id]
@values = TargetArea.where(:special_id => some_special_id)

respond_to do |format|
format.js { render 'make_a_change' } #make_a_change.js.erb
end
end

Then, I think you can just do the rest in your make_a_change.js.erb, which will run each time you call that other function and your Ajax request is successful.

var select2 = document.getElementById("target_area_id");
select2.options.length = 1;
select2.options[select2.options.length] = new Option(<%= @values.count %>,"1");

Tweak that to your needs. Hope this helps!


UPDATE:

I just realized this line:

select2.options[select2.options.length] = new Option(<%= @values.count %>,"1");

might not work. If it's an HTML select box or something similar, you could put it in its own view, and re-render it in make_a_change.js.erb in the proper spot.

Like so:

     $('#some_div').html('<%= j render 'select2_list', values:@values %>')

Mostly, the theme behind my answer is this: If you want to interact with your Ruby code or server data from a JavaScript function, which is some function called when you click a button or check a box or something along those lines, you will have to send an Ajax request to your server and handle the request in your controllers. That will then bring you closer to Rails and further from trying to link two different language variables with an = sign.

Using Ruby variable in Javascript (In App View)

Assuming the script tag you mentioned is in a html erb view you can just use this:

<script type="text/javascript" charset="utf-8">
var json = <%= @json || 'null' %>;
</script>

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.

use javascript variable inside ruby code

Ce ne pas possible, mon ami.


As mentioned in the comments, Ruby is server; javascript is client. This means one of two things:

  • build the javascript at runtime (not recommended)
  • send the ajax / javascript value to the server (via Ajax)

To get this working properly, you'll need to send the request through ajax:

#app/assets/javascripts/application.js
$(document).on("change", "#some_id", function(e) {
$.get("forms/update", {index: $(this).val(), value: $(this).attr('id').to_i});
});

This would need to be addressed by the appropriate route & controller action:

#config/routes.rb
get "color_form", to: "application#color_form"

#app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
respond_to :js, :html

def color_form
@id = params[:id]
@value = params[:value]
end
end

#app/views/application/color_form.js.erb
$('option_value_0').html('<%=j render partial: 'color_form', locals: { index: @index, id: @value } %>')

--

Yes, it's long-winded, but it's the right way.

If you wanted to shortcut, you'd be able to preload the color_form partial, and then use the javascript functionality to change the id or value params. I can write about this if you want.


Preload

If you wanted to do this without ajax, the standard way (this includes modals, too) is to append the partial to your page and "hide" it.

This way, your JS has the actual HTML code to either show, or append to other parts of the page:

#view
<div class="hidden">
<%= render partial: 'color_form', locals: { f: f, index: "x", id: "y" } %>
</div>

#app/assets/javascripts/application.js
$(document).on("change", "#some_id", function(e) {
$partial = $(".hidden").html();
$partial.find("#id").html($(this).attr('id').to_i);
$partial.find("#index").html($(this).val());
$('option_value_0').html($partial);
});

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 %>
<script>
$(document).ready(function(){
$("#category").change(function(){
var temp_name = $('#category').val();
$.ajax({
url: "/YOUR_PATH/"+temp_name,
dataType: "html",
type: "GET",
data: {ANY_DATA: VALUES},
success: function(data){
jQuery("#template_overview").html(data);
}
});
});
});
</script>
<% end %>

<div id="template_overview">
</div>

have a partial that populates your div

in the controller:

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

and of course the routes

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

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

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'
data:
param: variable
dataType: 'json'
success: (res) ->
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. :)

How to use a JavaScript variable in erb code in Rails?

You cannot do it because javascript run on client side while the code in ERB file runs at server side, you can send the value using ajax request,
Plus here is an awsome rails cast

Here is an example to send message from javascript to controller; When user click on apply we have an action 'set_id' in controller, it get the power, do the validations etc, the show the message in 'id_message' div in views.

  $('#apply').live('click', function(event, data, status, xhr) {
event.preventDefault();
return $.ajax({
url: '/users/registrations/set_id',
type: 'GET',
data: {
code: $('#user_id').val()
},
success: function(data, event, status, xhr) {
$('#id_message').html(response);
return $("#id_message").show();
},
error: function(event, data, status, xhr) {
$('#id_message').html(response);
return $("#id_message").show();
}
});
});

Hope it would answer your question



Related Topics



Leave a reply



Submit