Rails 4 and Basic Search Box with Ajax

Today, created a basic search page with rails 4 and Ajax.
Rails comes with ajax support. Adding remote => true to the action will make the action a ajax request instead of reloading the whole page.
This is what I did:
– In my home controller I have the index action, root points to index, so when index.html.erb renders I render the search box as follows:

<%= form_tag(‘/search’, remote: true) do %>
<%= text_field_tag :search, params[:search] %>
<%= submit_tag “Search”, :name => nil %>

<% end %>

– Since my form action says remote: true, this action will act as a ajax call.
– Added a search method in Home controller and also the route in route file

match ‘/search’, to: “home#search”, via: “post”

– The search mehtod just return the searched results in a instance variable @item which is available to the js view search.js.erb

$(‘#items’).html(‘<%= escape_javascript(render(“items”)) %>’);
$(‘#items’).show();

– The partial is a basic partial to render the results of the @items

Voila! It worked smooth..
Next, I want to add autocomplete in that search box.
🙂

Leave a comment