0

I have a form with 2 inputs and button. An user put feed url in the first input and press the button:

<%= link_to "get name", { :controller => 'Feeds', :action => "get_title" }, 
:remote => true, :class=>'btn btn-mini' %>       

Here is controller method

def get_title
   respond_to do | format |  
       format.js {render :layout => false}  
   end
end

And here is a get_title.js.erb:

var url = $( "#feed_url" ).val();
console.log(url);
$( "#feed_name" ).val("<%= @proxy.title(url) %>");

I get value of the first input and want to pass it as parameter to Ruby class. But in this case I get the error:

ActionView::Template::Error (undefined local variable or method `url' for #<#<Class:0x41ec170>:0x41ef968>):
    1: var url = $( "#feed_url" ).val();
    2: console.log(url);
    3: $( "#feed_name" ).val("<%= @proxy.title(url) %>");

Rails this that 'url' is a Ruby variable, but not JS one.

How can I pass JS variable to Ruby code ?

Thanks in advance.

2
  • Ruby runs on the server side. JS is on the client side. Thereby, it is a one way communication, and it is not possible to send informations from the view to the rails app. Commented Nov 21, 2012 at 6:42
  • Well, what is the best solution in this case? Make another one AJAX request using JS ? Commented Nov 21, 2012 at 7:09

1 Answer 1

1

Remember that any ERB (ruby) code is executed server side, while Javascript is, of course, rendered client side. As a result, your line <%= @proxy.title(url) %> is rendered WAY before that url value is ever evaluated. The solution to your situation is more along the lines of passing data to Rails, and rendering the response. Three things to facilitate this (bearing in mind that this is only one approach, and I'm sure there are plenty of others, and possibly better ways of doing this):

1- Your link_to won't post the user-input URL value because it is not POSTing the form. Instead, change the surrounding form to use :remote=true, and use a typical form.submit button rather than this link. Your form with the URL value will be submitted (and it will be asynchronous).

2- In your controller, render your title like you were trying to do, doing something along these lines:

def get_title
    render :text=>@proxy.title(params[:url])
end

3- Bind to the ajax:success event, something along these lines:

$("form#myForm").bind("ajax:success", function(event, data, status, xhr){
    $( "#feed_name" ).val(data) // data, in this case, is the rendered `@proxy.title(url)` we did in step 2.
})

Hope that makes sense. Let me know if it does not.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.