Bookmark this site!

2008-01-20

AJAX demystified: import xml

Here's the barebones of a javascript function that will request xml from a url configured to return xml (text/xhtml+xml or application/xml for example) and then asynchronously add a selected fragment of the returned xml as a child of some node on your page; this target node is selected by id.


function getXML(url, toGet, id){ 
  var request = new window.XMLHttpRequest();
   // for IE use ActiveXObject instead

  function load(){
      var content, node;
      if(request.readyState == 4 &&
         request.status == 200){
         content = document.adoptNode(
           request.responseXML.getElementById(toGet));
         node = document.getElementById(id);
         node.appendChild(content);
    } // should handle null response or failure
  }

  if(request){
      request.open("POST", url, true);
      request.setRequestHeader("Accept","application/xml");
      request.onreadystatechange=load;
      request.send(null);
  }// else ...
}

This will work on a gecko browser, if you have everything set up properly. You'll have to expand it to make it robust, as per the comments (and more).

Example xhtml to call this:

<div id="putInfoHere" />
<span class="button" 
  onmouseup='javascript:getXML(
    "http://my.site.net/contact.xhtml",
    "address",
    "putInfoHere");'>Get Info</span>

The file contact.xhtml should have an element such as <div id="address">...</div> with the matching id. This will be harvested. The clever part is that the harvested code still lives in the correct namespace. So imported markup is correctly interpreted as xhtml.

Make sure files are served with an appropriate mime-type. With apache you can do this using .htaccess :

AddType application/xhtml+xml .xhtml

A future post will have more, on how to send text or xml data to a script using httpRequest with POST instead of GET.

No comments: