Saggex
Saggex

Reputation: 3500

How to use variables from javascript in ruby?

In my edit.html.erb I'm using some javascript mixed with some ruby code:

var sel = document.getElementById("right").;
        var len = sel.options.length;
        var str = "";
        for (var i = 0; i < len; i++) 
                {
                if(sel.options[i].selected) 
                    {
                    <% RHoliday.find_or_create(holiday_id: sel.options[i].value , group_id: @group.id ) %> 
                    }
                }

        }

But I always get the following error:

undefined local variable or method `sel' for #<#:0x3f90ee8>

It's because I'm trying to access a variable from my javascript. My question is: Is there a way to get around this error?

Upvotes: 0

Views: 47

Answers (1)

Yule
Yule

Reputation: 9774

Short answer: You can't do this, JavaScript is client side, Ruby is server side.

Long answer:

You need to make an ajax call in your javascript rather than writing ruby explicitly into the function.

var sel = document.getElementById("right").;
var len = sel.options.length;
var str = "";
for (var i = 0; i < len; i++) 
{
  if(sel.options[i].selected) 
  {
    $.ajax("/holiday/create", {holiday_id: sel.options[i].value, group_id: @group.id}).done(function(data){
      //do something with data here
    });
  }
}

Then set up your routes and in your holiday controller:

def create
  render json: RHoliday.find_or_create(holiday_id: params[:holiday_id].to_s, group_id: params[:group_id].to_s)    
end

Don't suggest you use this exact code, but it gives you a starting point

Upvotes: 2

Related Questions