SNF Labs

happy jax

I redesigned the wiki yesterday to more closely resemble the main SNF Labs site, and also added a sitewide recent comments page, plus a “what links here” feature for every article.

The “what links here” feature provides a good chance to discuss when AJAX might be used and one way you can do it. My thought process went something like this: I could have put each article’s incoming links on a separate page, but since each page’s list of incoming links is likely to be small, it made more sense to display them on the same page as the article text. At the same time, I didn’t want an additional database query slowing down every page load, so I decided to make the list of incoming links only display when requested by the user. This required making an xmlhttprequest to the backend from the client-side code.

This is the Javascript code that does all the work:


function getIncomingLinks(articleName)
{
    var progress = document.getElementById('progress');
    var loadingMsg = document.createTextNode(" loading...");

    var loadingFunc = function(t) {
        progress.appendChild(loadingMsg);
    }

    var loadedFunc = function(t) {
        progress.removeChild(loadingMsg);
    }

    var errFunc = function(t) {
        alert('Error ' + t.status + ' -- ' + t.statusText);
    }

    var url = 'http://labs.spaceshipnofuture.org/icky/ajax.php';
    var params = 'mode=getIncomingLinks&q=' + articleName;
    var options = {
        method: 'get',
        parameters: params,
        onLoading: loadingFunc,
        onLoaded: loadedFunc,
        onFailure: errFunc
    }
    new Ajax.Updater('incoming-links', url, options);
}

This ought to be easy to follow. When the user clicks the “what links here” link, a call to getIncomingLinks() is made. getIncomingLinks() creates an Ajax.Updater object (part of the Prototype Javascript library). We provide Ajax.Updater with a URL to contact, the HTTP method to use (‘get’), and a number of callback functions that are triggered depending on the HTTP request state. When the request completes, Ajax.Updater updates the contents of the HTTP element with the id ‘incoming-links’ using whatever output the backend sent. That’s it.

The client-side code and backend code are rather tightly coupled here. If you don’t want the backend to send formatted output, you could use Ajax.Request instead and have the backend send its output as JSON. Your client-side code would then unpack the JSON output and format the data using the DOM.

 



Comments

posted 2005-10-25 01:51:21 by fhazel:

cool, thanks for the example. with video! i’m working on the script for adding new restaurants to rapacious chomping, i’ll see if i can figure out a way to use AJAX for validating the input without a bunch of page reloads.


Post a comment

You are not currently logged in. You need to have a registered SNF account to post a comment. (log in)