Creating a Small Library for AHAH
The Ajax applications examined in the last couple of lessons, although complete and functional, involved embedding a lot of JavaScript code into our pages. As you have seen, each application tends to contain similar functions:
A method to create an instance of the XMLHTTPRequest object, configure it, and send it
A callback function to deal with the returned text contained in the responseText property
You can abstract these functions into simple JavaScript function calls, especially in cases where you simply want to update a single page element with a new value returned from the server.
Introducing myAHAHlib.js
Consider Listing 13.1; most of this code will be instantly recognizable to you.
Listing 13.1. myAHAHlib.js
function callAHAH(url, pageElement, callMessage) { |
The function callAHAH() encapsulates the tasks of creating an instance of the XMLHTTPRequest object, declaring the callback function, and sending the request.
Note that instead of simply declaring
req.onreadystatechange = responseAHAH;
we instead used the JavaScript construct
req.onreadystatechange = function() {responseAHAH(pageElement);};
This type of declaration allows us to pass an argument to the declared function, in this case identifying the page element to be updated.
callAHAH() also accepts an additional argument, callMessage. This argument contains a string defining the content that should be displayed in the target element while we await the outcome of the server request. This provides a degree of feedback for the user, indicating that something is happening on the page. In practice this may be a line of text, such as
'Updating page; please wait a moment ....'
Once again, however, you may choose to embed some HTML code into this string. Using an animated GIF image within an <img> element provides an effective way of warning a user that a process is underway.
The callback function responseAHAH() carries out the specific task of applying the string returned in the responseText property to the innerHTML property of the selected page element pageElement:
output = req.responseText;
document.getElementById(pageElement).innerHTML = output;
This code has been packaged into a file named myAHAHlib.js, which you can call from an HTML page, thus making the functions available to your AHAH application. The next section shows some examples of its use.