-
Notifications
You must be signed in to change notification settings - Fork 13
Adding AJAX to site navigation
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_pagination
<%= ajax_pagination :pagination => "", :loadzone => true do %>
<%= yield %>
<% end %>
This simply names the section "" (it is recommended to name site-wide navigation with the empty string).
Now, we need to get the links to call AJAX Pagination when clicked. To do that, simply wrap your menu links with a container, with class="ajaxpagination", and data-pagination="". Normally your menu for site-wide navigation is in the same layout file.
<div class="ajaxpagination" data-pagination="">
<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>
</div>
The class activates AJAX Pagination, and the data-pagination attribute tells AJAX Pagination to put the new content inside the section named "".
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_pagination (normally we would specify the pagination name, but for this method, the default is :pagination => "":
class ApplicationController < ActionController::Base
ajax_pagination
...
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:
Although the default behaviour of the class method ajax_pagination, 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.
Use the ajax_link_to helper to ajaxify individual links. For more information, see Adding more links to site navigation.