Jump to content

How to make the back button accessible when using Ajax

+ 1
  sarahkim's Photo
Posted Jun 18 2010 01:07 PM

Populating web pages using Ajax creates a convenient, interactive user experience, which can’t be replicated with traditional HTTP requests. Unfortunately, each time you update the contents of the browser window with Ajax, that content becomes inaccessible to the back and forward buttons of your browser. The bookmarking functionality found in most browsers is also rendered nonfunctional. This excerpt from jQuery Cookbook shows you how to resolve these issues.

The solution to this problem is to relate each Ajax request to a unique URL. This URL can then be bookmarked and accessed by the back and forward browser buttons. One method for doing this is to use hash values. Hash values are generally used to link into a specific position within a document. http://en.wikipedia....i/Apple#History links to the history section of the Wikipedia page for Apple. For the purposes of this recipe, the hash value will refer to content loaded by an Ajax request.

In this example, the sample project is a small glossary. It has three entries. When you click each entry, the definition for the word is retrieved and displayed via Ajax. ranted, the content could easily be displayed all at once on a single page. However, this same approach is appropriate for larger, more varied data, such as the contents of each tab in a tabbed interface:

<!DOCTYPE html>
<html><head>
    <title>17. 6 Dealing with Ajax and the Back Button</title>
    <script src="../../jquery-1.3.2.min.js"></script>
    <script src="jquery.history.js"></script>
</head>
<body>
    <h1>17. 6 Ajax and the Back Button</h1>
    <a href="#apples" class='word'>apples</a>
    <a href="#oranges" class='word'>oranges</a>
    <a href="#bananas" class='word'>bananas</a>
    <p id='definition'></p>
</body></html>


Necessary Javascript files are included in the head of the document. The jquery.history.js file contains the jQuery history plugin (available at http://plugins.jquer...project/history). There is an anchor element for each of the three entries in the glossary. The definition for each entry will be displayed in the paragraph with an id of definition:

(function($) {
    function historyLoad(hash) {
        if(hash) { $('#definition').load('server.php',{word: hash}); }
        else { $('#definition').empty(); }
    }
    $(document).ready(function() {
        $.history.init(historyLoad);
        $('a.word').click(function() {
            $.history.load($(this).html());
            return false;
        });
    });
})(jQuery);


The history plugin has two functions that are of concern: init() and load(). The init() function is called inside the ready function. A callback to handle Ajax requests is passed in as an argument. load() is bound to the word links. The content of each anchor tag is passed in as an argument. The callback historyLoad() takes care of requesting the content for the passed-in hash value. It also needs to be able to handle instances where there is no hash value.

There are two instances when the historyLoad() callback is called. First, it is called inside the $.history.init() function, when the page is loaded. The hash value is stripped from the end of the URL and passed as the argument. If there is not a hash value present, the argument is empty. The load() function also calls historyLoad(). The argument we pass to $.history.load(), the word we clicked, in this case, is passed on as the hash argument to our callback.

In this solution, a jQuery plugin was used. It is relatively easy to implement similar functionality without a plugin, by using Javascript's window.location.hash object. The jQuery history plugin comprises only 156 lines of code. The reason it was chosen over writing a solution from scratch is that a large part of the plugin code handles crossbrowser inconsistencies. When handling browser differences, it’s often more effective to draw from the communal pool of experience that accumulates in a plugin than try and to account for every implementation discrepancy oneself.

jQuery Cookbook

Learn more about this topic from jQuery Cookbook.

Getting started with the jQuery library is easy, but it can take years to fully realize its breadth and depth; jQuery Cookbook shortens the learning curve considerably. You'll learn patterns and practices from 19 leading developers who use jQuery for everything from integrating simple components into websites and applications to developing complex, high-performance user interfaces. The recipes start with the basics and then move into practical use cases with tested solutions to common web development hurdles.

See what you'll learn


Tags:
1 Subscribe


0 Replies