StructureCMS

February 2, 2010

Enable AJAX on almost any site using jQuery

Filed under: AJAX — joel.cass @ 11:47 am

A website I was working on a while back had a requirement for an animated background to be running whilst users were on the website. The main problem was, that every time a user would click on a new page, the background would restart, interrupting the user experience and slowing things down in general. So what do we do? Inline frames? Create an AJAX service that returns the site content?

No, the answer is even simpler. Enter AJAX using jQuery. All you need is to have two div elements with identifiers surrounding the main content of your page, for example:

Example page structure

Example page structure

If you have the above structure and have the jQuery libraries loaded, then all you need to do is implement the following function:

function loadPage(URL) {
    $("#content-outer").load(URL + " #content", null, ajax_loaded);
    return false;
}

JQuery uses css selectors to identify elements, e.g. <div id=”content”> = #content, so what this function does is it looks up the element #content-outer, executes the AJAX request, and then looks up the #content element from the next page and replaces the contents of the #content-outer element with the new element, as demonstrated in the below diagram.

How requests are made using jQuery

How requests are made using jQuery

I have also added the following routine that will be called on startup. It effectively adds the loadPage(URL) method to each link’s onclick method. Because loadPage(URL) returns false, when the link is clicked, the AJAX call will be initialised and the user’s action will be cancelled.

function check_on_load() {
    // update links
    updateLinks("A");
}

$(document).ready(check_on_load);

function updateLinks(DOMLocation) {
    var links = $(DOMLocation);
    var baseURL = location.protocol + "//" + location.host + "/";
    for (var i = 0; i < links.length; i++) {
        var el = links[i]
        /* exclusions to the rule
         * - onclick must be null,
         * - url must contain the site's base url (http://site_domain)
         * - url cannot already have an anchor
         * - target must be empty
         * - classname must not contain 'no-ajax'
        */
        if (el.onclick == null &&
                el.href.indexOf(baseURL) == 0 &&
                el.href.indexOf("#") < 0 &&
                el.target == "" &&
                el.className.toLowerCase().indexOf("no-ajax") < 0) {
            el.onclick = Function("return loadPage(this.href);");
        }
    }
}

Furthermore, I have also added a callback to the method which will update the page title and replace any links within the new page content.

function ajax_loaded(responseText, textStatus, XMLHttpRequest) {
    if (textStatus == "error") {
        prompt("URL Failed: ", XMLHttpRequest);
    } else {
        // set title
        document.title = titleFromHTML(responseText);
        // update links
        updateLinks("#content-outer A");
    }
}

function titleFromHTML(HTML) {
    var regex = new RegExp("");
    var matches = regex.exec(HTML);
    if (matches.length > 1) {
        return matches[1];
    } else {
        return "";
    }
}

...And the best part? By simply including the script within your page along with jQuery (and making sure that your structure is correct), you will instantly enable AJAX-based loading on your page. Even better, if your browser does not fully support AJAX, javascript, or jQuery, all links will remain untouched and function just as they normally do.

Download jQuery here: http://docs.jquery.com/Downloading_jQuery
Download the script here: ajax-plugin_no_history.js
Demo: demo_no_history.htm

The only thing I have left out of this is history management. By using the script above, users lose the ability to switch back and forth between pages. By using the jQuery history plugin, you can give users the ability to switch back and forth between pages, and also the ability to bookmark AJAX'd pages.

Download jQuery history plugin here: http://www.mikage.to/jquery/jquery_history.html
Download the history enabled script here: ajax-plugin_with_history.js
Demo: demo_with_history.htm

1 Comment »

  1. hello. everything is fine.
    but not going with pages. php
    You can help.

    Comment by oscar — March 1, 2013 @ 3:50 am

RSS feed for comments on this post. TrackBack URL

Leave a comment