Example 2: Ajax with Nodes

Let’s alter the example, and instead of returning a string from the server, this time, make it XML:

<file>
  <name>
    <first>Bob</first>
    <last>Smith</last>
  </name>
  <address>
    <street>123 School Street</street>
    <city>Anytown</city>
    <state>NY</state>
    <zip>12345</zip>
  </address>
</file>

The XHTML page remains the same, but we need to make some minor adjustments to the JavaScript. To highlight the differences, I will touch on each change individually.

The first change, to the onchange event handler of the select, is pretty simple:

...
    addressBook.addEvent( addressBook.control,
                          'change',
                          function(  ){
                            if( this.value != '' ){
                              addressBook.getAddress( this.value );
                            } else {addressBook.target.removeChild(
                                addressBook.target.firstChild );
                            }
                          } );
...

Instead of setting the content of the target to empty using innerHTML, the DOM is removing the node that is the target’s first child.

Next up is the getAddress( ) method:

...
  getAddress:  function( id ){
    addressBook.buildLoader(  );
    var fnWhenDone = function(oXML) {
      addressBook.killLoader(  );if( addressBook.target.hasChildNodes(  ) ){
        addressBook.target.removeChild( addressBook.target.firstChild );
      }
      xml = oXML.responseXML; var name = addressBook.getNodeValue( xml, 'first' ) + ' ' + addressBook.getNodeValue( xml, 'last' ); var address = addressBook.getNodeValue( xml, 'street' ); var csz = addressBook.getNodeValue( xml, 'city' ) + ', ' + addressBook.getNodeValue( xml, 'state' ) + ' ' + addressBook.getNodeValue( xml, 'zip' ); var txt ...

Get Web Design in a Nutshell, 3rd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.