Skip to content

AJAX call in Rails 3 ( using .load method)

richlewis14 edited this page Nov 13, 2012 · 2 revisions

In this example we have a search form that performs a GET request and then displays the results on the same page, before this method was implemented the results would appear on a separate page.

The Form

The most important part of this form is the

:remote => true

This prevents the default behaviour of the GET request, much like event.preventDefault does in jquery for preventing default actions on an anchor tag

  <%= form_tag({:controller => 'search', :action => 'search'}, {:method => 'get', :remote => true })  do |select| %>

We place to partial for the searchresults within the search controller, action search

  render :partial => 'shared/searchresults'

The Jquery/AJAX call

$(document).ready(function() {
 $('.searchbutton').click(function() {
  $('#searchres').load('search');
  });
  });

This basically says when the search button is clicked load the contents of 'search' into the div id of 'searchres'

The View

<div class="container">
 <div class="row">
  <div class="span6">
   <h3>Search Recipes here</h3>
    <%= render 'shared/searchrecipes' %>
     <div id ="searchres"></div>
  </div>
 </div>
</div>