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:
<%= link_to "Search", "#", :id => "search_geocode", :"data-href" => my_controller_geocode_path %>
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):
$('#search_geocode').live('click', function(event){
event.preventDefault();
$.post($(this).attr('data-href') + "?address=" + $('#address').val(), function(data){} );
});
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 the data-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 this id
attribute needs to change based on some sort of page template conditions, you could expand on my example by adding another data-
parameter to your link. For example:
<%= link_to "Search", "#", :id => "search_geocode", :"data-href" => my_controller_geocode_path, :"data-address-id" => address_helper_id %>
And again, in application.js
replacing above with something along the lines of:
$('#search_geocode').live('click', function(event){
event.preventDefault();
$.post($(this).attr('data-href') + "?address=" + $($(this).attr('data-address-id')).val(), function(data){} );
});
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.
$('<id of the form').bind('ajax:success', function(event, data, status, xhr) {
... process your data here ...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With