AJAX with XML Demo App

This demo app shows how the AJAX script could be used for an online address book. Click on a contact in the left column and an AJAX request is sent. The response is used to populate the contact details column.

The benefits of this approach are super fast response times for the user and less bandwidth and server resources used to supply the response.


Contact Details

Name :
Address :
Phone :
Fax :

To get the AJAX script used in this example go to the AJAX tutorial..

You can see a simpler example that updates the page but doesn't use XML at the AJAX Demo App.

You can see a basic example at the Simple AJAX Demo page.

A look at the code

The AJAX script makes the code needed for this demo app very simple.

This first section just initializes the onclick handler for each list item in the contacts div.

function init() { var contacts = document.getElementById('contacts').getElementsByTagName('li'); var length = contacts.length; for (var i=0; i < length; i++) contacts[i].onclick = contactClick; } window.onload = init;

This is the function that sends the AJAX request and handles the response.

function contactClick(e)
// define a response handler.
function responseHandler(ajaxRequest)
// get the XML document from the request
var responseXML = ajaxRequest.responseXML.documentElement;

// Grab the data from the XML document and put it into our contact fields.
document.getElementById('name').value =
getXMLEntries(responseXML, 'name')[0];

document.getElementById('address').value =
getXMLEntries(responseXML, 'address')[0];

document.getElementById('phone').value =
getXMLEntries(responseXML, 'phone')[0];

document.getElementById('fax').value =
getXMLEntries(responseXML, 'fax')[0];

// send the AJAX request
ajaxSend('get', 'http://dynamictable.com/contactDetails.aspx',
'contactId=' + this.getAttribute('contactId'), responseHandler);

As you can see this code is very clean and easy to understand. The AJAX script makes sending the AJAX request and handling the response a breeze. The response handler makes use of the getXMLEntries helper function which is also defined in the AJAX script.

A note on validation

I'm sure there are a few people out there keen to point out that adding arbitrary attributes (contactId) to the list item elements stops this page from validating.

I know and I don't care. I could have stuffed the data into a valid attribute (like title) but in my opinion it is worse to have valid markup that's logically incorrect than it is to have invalid, but logical, markup.


If you've got any questions or feedback about this article please post them in the Dynamic Tools Javascript Forum.