I want to make an in-place search in my rails app.
I used button_to_remote with prototype, but now I'm using JQuery, so I changed to link_to.
This is my code:
<%= link_to "Search", {:action => "geocode", :with => "'address='+$('#{address_helper_id}').value"}, :method => :post, :remote => true %>
I want to pass the address textfield to my controller, but the output is not what I expected.
/mycontroller/geocode?with=%27address%3D%27%2B%24%28%27record_location___address%27%29.value
How do I submit my value?
You might want to try approaching things a little more unobtrusively. I would recommend replacing your
link_to
call with something like:This is virtually identical to what you already have, except that it includes a unique id, and also the controller/geocode path in an
data-href
attribute. This will help allow you to keep your ruby and javascript a bit more separated.Then in your
application.js
(or somewhere similar):What this is effectively doing is binding a
click
event listener to your search button, which posts the address to the url or path provided in thedata-href
attribute of your search link.I also notice that in your code, you're setting the
id
of the source address in ruby. If thisid
attribute needs to change based on some sort of page template conditions, you could expand on my example by adding anotherdata-
parameter to your link. For example:And again, in
application.js
replacing above with something along the lines of:This isn't exactly a direct answer to your question, but have you looked into jrails? It allows you to use the same prototype javascript helpers that you were using before you switched over to jquery. It made my transition from prototype to jquery much easier.
The easiest way is to put the search field and the submit button in a normal form (using the default rails view helpers). And you add the
:remote => :true
option to the form. See form_for url helper for the docs.I gueuss you already added the jquery specific rails.js file.
Doing it like this will automatically post the form via ajax to the given action.
After that, you only need a 'ajax:success' event handler so that you can handle the data.
You can try this:
<%= text_field_tag :address %>
<%= submit_tag "Search", :id => "search_button" %>