Skip to content

Adding AJAX to site navigation

Ronald Chan edited this page Mar 20, 2012 · 13 revisions

This is the recommended way to add AJAX to site navigation, and assumes that you have already installed AJAX Pagination. Some steps could be skipped, but would also miss some highly recommended features.

We need to let AJAX Pagination know what part of the page should be reloaded when the site is navigated. We can do this in your application layout. By wrapping the

<% yield %>

command with a call to ajax_section:

<!-- /app/views/layouts/application.html.erb -->
...
<%= ajax_section :id => "global", :loadzone => true do %>
  <%= yield %>
<% end %>

For the purpose of this guide, we are naming the AJAX section "global", however, the default id is "global". Similarly the default :section_id for ajax_link_to, ajax_form_for, ajax_form_tag and ajax_options methods, is also "global". This means that they can be left out to save typing.

Now, we need to get the links to call AJAX Pagination when clicked. To do that, simply wrap your menu links with ajax_links. Normally your menu for site-wide navigation is in the application layout file also.

<!-- /app/views/layouts/application.html.erb -->
...
<%= ajax_links :section_id => "global", :class => "menu" do %>
  <ul>
    <li><%= link_to "Home", root_url %></li>
    <li><%= link_to "Posts", posts_url %></li>
    <li><%= link_to "Changelog", changelog_url %></li>
    <li><%= link_to "Readme", pages_readme_url %></li>
    <li><%= link_to "About", pages_about_url %></li>
  </ul>
<% end %>
...
<%= ajax_section :id => "global", :loadzone => true do %>
  <%= yield %>
<% end %>

Wrapping with ajax_links will automatically convert all plain links into AJAX links, and load the content into the section specified by :section_id.

Finally, it is highly recommended to get AJAX Pagination to detect and respond to the AJAX call (at the moment it simply retrieves the whole page, and selects the specific content required).

You can do this in the ApplicationController, by calling ajax_respond:

# /app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
  ajax_respond :section_id => "global"

  ...
end

This just modifies the default_render behaviour when the request is an AJAX call, to only return the view template, without the layout.

It should now paginate with AJAX, below is a site with this implemented: Site loading Readme page using AJAX Pagination

Layout

Although the default behaviour of the class method ajax_respond, which detects and responds to AJAX requests, is to use no layout, it is highly recommended that a layout is used. To learn more, see Using a layout in site navigation.

What about other links?

Use the ajax_link_to helper to ajaxify individual links. For more information, see Adding more links to site navigation.