Accessing JavaScript Variable from 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.

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.

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);
});

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'

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>


Related Topics



Leave a reply



Submit