AJAX – What's The Buzz – part two (slightly more in depth, on challenges and solutions)


In a previous article (AJAX – What’s the Buzz Part 1), we discussed the introduction to AJAX as a Design Pattern. We saw a simple demonstration leading up to why we might need something like AJAX ‘mechanisms’ and how these can be implemented. The article was basically a report from the session and workshop we had last week at AMIS. In this article, I will continue with the report, telling you about the discussion and brainstom we had, as well as the more advanced examples of AJAX usage.

We had discussions on what would we use Ajax for in the type of web applications we typically develop, what are the additional challenges using Ajax will have us face and how do we tackle some obivous technical issues such as multiple parallel requests, repeating requests (for tickers or pollers) and requests to other domains than the one the base document was loaded from (the cross domain browser issue). We also discussed a number of libraries and frameworks that may help us in doing Ajax style development. Note however that most of these frameworks are primarily JavaScript libraries, not necessarily Ajax libraries.



Hello World in Ajax programming

Where would we be without Hello World – Ajax style? So here we go – simplest Ajax application man can come up with. Or at least close to it. A very simple HTML document – we have left out the JavaScript.

&lt;html xmlns=&quot;http://www.w3.org/1999/xhtml&quot;&gt; <br />&lt;head&gt; <br />  &lt;title&gt;Simple XMLHttpRequest&lt;/title&gt; <br />  &lt;script type=&quot;text/javascript&quot;&gt; …&lt;/script&gt;<br />&lt;/head&gt; <br />&lt;body&gt; <br />  &lt;form action=&quot;#&quot;&gt; <br />    &lt;input type=&quot;button&quot; value=&quot;Start Basic Asynchronous Request&quot; onclick=&quot;startRequest();&quot;/&gt; <br />  &lt;/form&gt; <br />&lt;/body&gt;<br />&lt;/html&gt; &nbsp;<br />

When viewed in the browser, this page looks like:


(click on the image for a live demo) 

Now let’s flesh out that piece of JavaScript: the startRequest() method:

&lt;script type=&quot;text/javascript&quot;&gt; <br />var xmlHttp; <br /><br />// this function initializes the xmlHttp variable in a cross browser fashion<br />function createXMLHttpRequest() { <br />  if (window.ActiveXObject) { <br />       xmlHttp = new ActiveXObject(&quot;Microsoft.XMLHTTP&quot;); <br />  } else if (window.XMLHttpRequest) { <br />      xmlHttp = new XMLHttpRequest(); <br />    }  <br />} <br /><br />// this function initiates the Ajax request (cycle) by first initializing the xmlHttp object <br />// that contains the request and response, setting its main properties and sending the request<br />function startRequest() { <br />  createXMLHttpRequest(); <br />  // specify (callback) function to handle response<br />  xmlHttp.onreadystatechange = handleStateChange;<br />  // GET or POST, what is the URL, Asynch or Synch<br />  xmlHttp.open(&quot;GET&quot;, &quot;simpleResponse.xml&quot;, true); <br />  xmlHttp.send(null); <br />} <br /><br />// the callback function that is called upon any change in the state of the xmlHttp object.<br />// Note: these state changes occur at various times during the Http request/response cycle.<br />function handleStateChange() {      <br />  ...<br />}//handleStateChange<br />&nbsp;

The final piece of code is what gets called once the Ajax request-cycle is complete:

<br />function handleStateChange() { <br />  if ( xmlHttp.readyState == 4) { <br />     if ( xmlHttp.status == 200) { <br />        alert(&quot;The server replied with: &quot; + xmlHttp.responseText); <br />     } <br />  } <br />} <br />&lt;/script&gt; <br />

Here the state changes in the xmlHttp object are tracked; once we get to status 4 (done) and code 200 (successful) we know we have a response in that we can start to process. The alert displayed in the browser after pressing the button and a very brief delay looks like this:


Now it does not get any simpler or less useful. But this is the bare essence of Ajax: it is asynchronous (the user had not idea you were doing communication with the web server in the background) and it is plain JavaScript.

DOM manipulation using the Ajax Response

Showing an alert with the response received to our Ajax request is probably one of the lousiest things we can do. If that is what Ajax was all about, you might as well stop reading right now. Of course there is much more than this. Responses to Ajax requests can be used in any way you like and the two most obvious usages are: store the result in JavaScript memory structures for later use or inject into the current page through DHTML to for direct presentation to the user. DHTML is another of those mythical concepts that on close inspections turns out to be not much more than programmatic access to the Browser’s DOM. That in itself is pretty terrific by the way (since IE 4.0 and Netscape 4.0, 1997 or so), but nothing changed in HTML or CSS or even in JavaScript – accept for some operations on the document object. 

We will most definitely not embark on a broad discussion on DHTML or even the DOM, but we will take a look at a simple example of using DHTML or displaying the Ajax response to the user. We have the same page as before, with the humongous button. This time we will not be so crude as to display the Ajax response in an Alert. We will be sophisticated and use DHTML to show the response dynamically in our document. (note: you can click on the image for a live demo).

We have made two subtle changes to the HTML document: we have added a STYLE definition:

&lt;style type=&quot;text/css&quot;&gt;<br />    hidden  { display:none}<br />    visible  { display:block}<br />&lt;/style&gt;<br />&nbsp;

and we have inserted a DIV element – that for the moment is invisible -:

    &lt;div id=&quot;content&quot; style=&quot;background-color:pink;font-family:sans-serif&quot; <br />         class=&quot;hidden&quot;&gt;<br />    &lt;/div&gt;<br />&nbsp;

The code responsible for handling the Ajax response in such a refined way is as follows:

&nbsp;function el(id) {<br />  return document.getElementById(id);<br />}<br />    <br />function handleStateChange() {<br />    if(xmlHttp.readyState == 4) {<br />        if(xmlHttp.status == 200) {<br />          el('content').innerHTML = xmlHttp.responseText;<br />          el('content').setAttribute(&quot;className&quot;,&quot;visible&quot;);<br />        }<br />    }<br />}<br /><br />

Note that we have been somewhat lazy by just using the innerHtml property (once an IE only pollution of DHTML). There are more refined ways to programmatically create DOM elements, as we will see shortly.

Operations and properties on DOM elements that may come on handy include:


  • document.getElementById(id)
  • element.getElementsByTagName(tagName)
  • document.createElement(tagName)
  • document.createTextNode(text)
  • element.appendChild(childNode)
  • element.getAttribute(attributeName)
  • element.s
    etAttribute(attributeName, newValue)<
  • element.insertBefore(newNode, targetNode)

Properties of DOM elements: parentNode, childNodes (Array of nodes), firstChild, lastChild, nextSibling, previousSibling, nodeValue

The next example shows an amalgation of two samples from the book Foundations of Ajax (see Resources). It illustrates a combination of an Ajax request to retrieve data depending on a selection made by the user with dynamically creating DOM nodes to display a table with these values. For a live demo of this example, see here: http://www.amis.nl//files/technology/ajaxBuzz/DHTMLCreatingNodes/parseXMLandDHTML.html.

This page contains two parts: the Ajax request and the DOM Manipulation. First the Ajax stuff:

var xmlHttp;<br />var requestType = &quot;&quot;;<br /><br />function createXMLHttpRequest() {<br />    if (window.ActiveXObject) {<br />        xmlHttp = new ActiveXObject(&quot;Microsoft.XMLHTTP&quot;);<br />    } <br />    else if (window.XMLHttpRequest) {<br />        xmlHttp = new XMLHttpRequest();<br />    }<br />}<br />    <br />function startRequest(requestedList) {<br />    requestType = requestedList;<br />    createXMLHttpRequest();<br />    xmlHttp.onreadystatechange = handleStateChange;<br />    xmlHttp.open(&quot;GET&quot;, &quot;parseXML.xml&quot;, true);<br />    xmlHttp.send(null);<br />}<br />    <br />function handleStateChange() {<br />    if(xmlHttp.readyState == 4) {<br />        if(xmlHttp.status == 200) {<br />            if(requestType == &quot;north&quot;) {<br />                listStatesInRegion(&quot;north&quot;);<br />            }<br />            else if(requestType == &quot;south&quot;) {<br />                listStatesInRegion(&quot;south&quot;);<br />            }<br />            else if(requestType == &quot;all&quot;) {<br />                listAllStates();<br />            }<br />        }<br />    }<br />}<br />&nbsp;

The startRequest() function is invoked from the onClick event handler on each of the three buttons, for example:

&nbsp;&lt;input type=&quot;button&quot; value=&quot;View All Listed Northern States&quot; onclick=&quot;startRequest('north');&quot;/&gt;

The table with the names of the selected states is (re)created dynamically when the XML data is received in the Ajax response:

function listStatesInRegion(region) {<br />    var xmlDoc = xmlHttp.responseXML;<br />    var regionNode = xmlDoc.getElementsByTagName(region)[0];<br />    var regionStates = regionNode.getElementsByTagName(&quot;state&quot;);<br />    parseResults(regionStates);    <br />}<br /><br />function listAllStates() {<br />    var xmlDoc = xmlHttp.responseXML;<br />    var allStates = xmlDoc.getElementsByTagName(&quot;state&quot;);<br />    parseResults(allStates);    <br />}<br /><br />function clearPreviousResults() {<br />    var header = document.getElementById(&quot;header&quot;);<br />    if(header.hasChildNodes()) {<br />        header.removeChild(header.childNodes[0]);<br />    }<br /><br />    var tableBody = document.getElementById(&quot;resultsBody&quot;);<br />    while(tableBody.childNodes.length &gt; 0) {<br />        tableBody.removeChild(tableBody.childNodes[0]);<br />    }<br />}<br /><br />function parseResults(states) {<br />    clearPreviousResults();<br />    var state = null;<br />    var name = &quot;&quot;;<br />    for(var i = 0; i &lt; states.length; i++) {<br />        state = states[i];<br />        name = state.childNodes[0].nodeValue;<br />        <br />        addTableRow(name);        <br />    }<br />    <br />    var header = document.createElement(&quot;h2&quot;);<br />    var headerText = document.createTextNode(&quot;Results:&quot;);<br />    header.appendChild(headerText);<br />    document.getElementById(&quot;header&quot;).appendChild(header);    <br />    document.getElementById(&quot;resultsTable&quot;).setAttribute(&quot;border&quot;, &quot;1&quot;);<br />}<br /><br /><br />function addTableRow(name) {<br />    var row = document.createElement(&quot;tr&quot;);<br />    var cell = createCellWithText(name);<br />    row.appendChild(cell);  <br />    document.getElementById(&quot;resultsBody&quot;).appendChild(row);<br />}<br /><br />function createCellWithText(text) {<br />    var cell = document.createElement(&quot;td&quot;);<br />    var textNode = document.createTextNode(text);<br />    cell.appendChild(textNode);    <br />    return cell;<br />}<br /><br />

The relevant section of the HTML document is this fragment:

  &lt;span id=&quot;header&quot;&gt;<br />  &lt;/span&gt;<br /><br />  &lt;table id=&quot;resultsTable&quot; width=&quot;75%&quot; border=&quot;0&quot;&gt;<br />    &lt;tbody id=&quot;resultsBody&quot;&gt;<br />    &lt;/tbody&gt;<br />  &lt;/table&gt;<br />&nbsp;

Bringing Server Side Validation to the Client

An example of how Ajax can be used to increase the interactivity of our web applications using Ajax is performing server side validation through asynchronous requests whenever the user has changed a field. In the next example, the end user can create a new Employee. One of the properties to be provided for new employees is their Job. However, even though we have not created a Select element for Job, there still is a restriction on the job title we can assign to new employees. We have linked the onChange event of the Job field to a JavaScript function that makes an Ajax request to a server side Servlet, passing the Job as entered by the User. The Servlet will validate the Job title using the same code that normally does the server side validation of this particular field. If the validation is successful- the response is ignored in the browser. However, when the value typed in by the user is not a valid one, a validation error will be prresented to the end user, within seconds or even a fraction of a second after leaving the Job field.

Now the validation error is presented:

The relevant JavaScript code in the HTML document:


var xmlHttp;<br /><br />function createXMLHttpRequest() {<br />    if (window.ActiveXObject) {<br />        xmlHttp = new ActiveXObject(&quot;Microsoft.XMLHTTP&quot;);<br />    } <br />    else if (window.XMLHttpRequest) {<br />        xmlHttp = new XMLHttpRequest();<br />    }<br />}<br />    <br />function startRequest(url) {<br />    createXMLHttpRequest();<br />    xmlHttp.onreadystatechange = handleStateChange;<br />    xmlHttp.open(&quot;GET&quot;, url, true);<br />    xmlHttp.send(null);<br />}<br />    <br />function el(id) {<br />  return document.getElementById(id);<br />}<br />    <br />function handleStateChange() {<br />    if(xmlHttp.readyState == 4) {<br />        if(xmlHttp.status == 200) {<br />          var response = xmlHttp.responseText;<br />          if (response.toLowerCase().indexOf(&quot;error&quot;)&gt;-1) {<br />             el('errorbox').innerHTML = xmlHttp.responseText;<br />             el('errorbox').setAttribute(&quot;className&quot;,&quot;visible&quot;);<br />          }<br />          else {<br />            el('errorbox').innerHTML = '';<br />            el('errorbox').setAttribute(&quot;className&quot;,&quot;hidden&quot;);<br />          }<br />        }<br />    }<br />}<br /> <br />function validateJob(job) {<br />   startRequest(''+job);<br />}<br />...<br />&lt;div id=&quot;errorbox&quot; class=&quot;hidden&quot; style=&quot;background-color:rgb(255,0,0); color:rgb(255,255,0); font-family:sans-serif; font-size:large;&quot;&gt;&lt;/div&gt;        <br />...<br />&lt;td width=&quot;21%&quot;&gt;<br />            &lt;h3&gt;<b
r />
         Job<br />            &lt;/h3&gt;&lt;/td&gt;<br />        &lt;td width=&quot;29%&quot;&gt;<br />            &lt;input type=&quot;text&quot; id=&quot;job&quot; name=&quot;job&quot; size=&quot;20&quot; onchange=&quot;validateJob(this.value);&quot;/&gt;<br />          &lt;/td&gt;<br />&nbsp;

The servlet that performs the validation – very simplistic of course:

package nl.amis.ajaxbuzz;<br /><br />import java.io.IOException;<br />import java.io.PrintWriter;<br /><br />import javax.servlet.*;<br />import javax.servlet.http.*;<br /><br />public class ValidateJob extends HttpServlet {<br />    private static final String CONTENT_TYPE = &quot;text/text; charset=windows-1252&quot;;<br /><br />    public void init(ServletConfig config) throws ServletException {<br />        super.init(config);<br />    }<br /><br />    final static String[] jobs = new String[]{&quot;manager&quot;,&quot;consultant&quot;,&quot;expertise manager&quot;,&quot;cook&quot;,&quot;people manager&quot;,&quot;programmer&quot;,&quot;account manager&quot;,&quot;teacher&quot;};<br /><br />    private boolean notValid(String job) {<br />        for (int i=0;i&lt;jobs.length;i++) {<br />          if (jobs[i].equalsIgnoreCase(job))<br />            return false;<br />        }<br />        return true;<br />    }<br /><br />    public void doGet(HttpServletRequest request, <br />                      HttpServletResponse response) throws ServletException, <br />                                                           IOException {<br />        String job = &quot;&quot;;<br />        job = request.getParameter(&quot;job&quot;);<br />        response.setContentType(CONTENT_TYPE);<br />        PrintWriter out = response.getWriter();<br />        if (notValid(job) ) {<br />          out.println(&quot;Validation Error in the value for Job: &lt;i&gt;&quot;+job+ &quot;&lt;/i&gt; unfortunately is not a valid value! Please try again.&quot;);<br />        }<br />        else {<br />          out.println(&quot;Validation of Job (value=&quot;+job+&quot;was successful.&quot;);                    <br />        }<br />        out.close();<br />    }<br />}<br />&nbsp;

Discussion: what do we use Ajax for and what are the challenges it brings?

 Having seen some examples of famous Ajax applications (see the first installment Ajax What’s the Buzz) and now having taken an more in depth look at what you can do and how you can do it, we discuss the potential for Ajax in our own applications. We typically develop data oriented OLTP style administrative web applications using Java/J2EE technology. How does Ajax fit in with that type of application?

Obvious usages of Ajax include:

  • Complex Validations – client side validations that are really server side validations
  • Suggestions (code completion)
  • Dynamic Lists of Values (list is adapted based on user action in the current page)
  • Trees – dynamic loading of expanded nodes
  • Client Side content aggregation and integration (collect content from various sources and combine in the client)
  • Post Loading large resources
  • Client Side Web Service calls
  • “Tickers” – repetitive, polling calls
  • Partial Page Refresh
  • Visual, dynamic enhancements
  • Fewer pages, more functionality per page

Although Ajax may seem very simple to implement, looks can deceive. Implementing a single Ajax request for a single page is quite innocent. However, moving towards a more dynamic, interactive, fewer-page-application requires a radical change in the way we design and implement applications. And typical server side frameworks like Struts and JSF may not be optimally equiped for this new approach. Some of the challenges associated with Ajax we discussed in our workshop:

  • Implement Professional Software Engineering with  JavaScript now that more of the application will be client side/browser based
  • Prototyping and Functional (interaction) Design – static HTML and frequent full page refresh will not do at all!
  • Respective Roles of Client and Server – what will happen where
  • Complexity of the application – for development & maintenance and for the end user!
  • Back Button – what does it mean to push the Browser’s back button in a Single Page Application?
  • Single Page Application!?
  • Danger of going completely overboard with Ajax: it can be done, so we will do it!

There does seem to be some good news on the first issue: JavaScript development is definitely getting more professional. More tools – IDEs, debuggers (Venkman), browser plugins (especially Firefox) – that better support JavaScript development, more and very professional libraries and frameworks and counterparts for key software engineering components in other technology realms, such as JSDoc, JSUnit (and Selenium) and JSLint.

However we still must take a lot of care, as well as hone our JavaScript programming skills, to make sure we work in a structured, well designed way with JavaScript. I am constantly surprised at the richness of the JS language – the way OO concepts can be applied, the flexibility and the dangers following from that flexibility.


Multiple, simultaneous or Parallel Requests – Introducing some structure to our Ajax world

So far, we have had very simple Ajax applications with only one Ajax request at the time. Or at least that was our assumption. In the validation example we saw before, if we had added a server side validation cycle for the Salary field and we had a quick typist, we might have run into problems: after leaving the changed Job field, an Ajax request would be sent, using the global xmlHttp variable. Then, if the user would change and leave the salary field before the response to this request was in, we would reuse this variable to fire another Ajax request, this time to validate the Salary. We would have lost our hold on the original Job validation request and would not be able to present a warning to end user if that validation failed.

Basically, we cannot handle more than one Ajax request at a time. Which of course is a severe limitation. So what can we do? Well, more structure, more encapsulation, a bit of OO and some inspiration from the Ajax in Action book. Following the example in the book, we create a very simple JavaScript library with a very simple ‘framework’ – it is so small it does not really deserve that name – for making Ajax requests. Two important characteristics: Each request is an Object instance in its own right (no more global variable) and the Callback function has direct access to the request object, instead of through the global variable.

The code in the ContentLoader.js library is somewhat terse – but it does the job:

/* namespacing object */<br />var net=new Object();<br /><br />net.READY_STATE_UNINITIALIZED=0;<br />net.READY_STATE_LOADING=1;<br />net.READY_STATE_LOADED=2;<br />net.READY_STATE_INTERACTIVE=3;<br />net.READY_STATE_COMPLETE=4;<br /><br /><br />/*--- content loader object for cross-browser requests ---*/<br />net.ContentLoader=function(url,onload,onerror,method,params,contentType){<br />  this.req=null;<br />  this.onload=onload;<br />  this.onerror=(onerror) ? onerror : this.defaultError;<br />  this.loadXMLDoc(url,method,params,contentType);<br />  this.parameter = null;<br />}<br /><br />net.ContentLoader.prototype.loadXMLDoc=function(url,method,params,contentType){<br />  if (!method){<br />    method=&quot;GET&quot;;<br />  }<br />  if (!contentType &amp;&amp; method==&quot;POST&quot;){<br />    contentType='application/x-www-form-urlencoded';<br />  }<br />  if (window.XMLHttpRequest){<br />    this.req=new XMLHttpRequest();<br />  } else if (window.ActiveXObject){<br />    this.req=new ActiveXObject(&quot;Microsoft.XMLHTTP&quot;);<br />  }<br />  if (this.req){<br />    try{<br />      var loader=this;<br />      this.req.onreadystatechange=function(){<br />
  net.ContentLoader.onReadyState.call(loader);<br />      }<br />      this.req.open(method,url,true);<br />      if (contentType){<br />        this.req.setRequestHeader('Content-Type', contentType);<br />      }<br />      this.req.send(params);<br />    }catch (err){<br />      this.onerror.call(this);<br />    }<br />  }<br />}<br /><br />net.ContentLoader.onReadyState=function(){<br />  var req=this.req;<br />  var ready=req.readyState;<br />  if (ready==net.READY_STATE_COMPLETE){<br />    var httpStatus=req.status;<br />      if (httpStatus==200 || httpStatus==0){<br />        this.onload.call(this);<br />      }<br />      else {<br />        this.onerror.call(this);<br />      }<br />  }<br />}<br /><br />net.ContentLoader.prototype.defaultError=function(){<br />  alert(&quot;error fetching data!&quot;<br />    +&quot;\n\nreadyState:&quot;+this.req.readyState<br />    +&quot;\nstatus: &quot;+this.req.status<br />    +&quot;\nheaders: &quot;+this.req.getAllResponseHeaders());<br />}<br />&nbsp;

The main "trick" in this piece of code is in the definition of the callback function on the XmlHttpRequest object:

var loader=this;<br />this.req.onreadystatechange=function(){<br />        net.ContentLoader.onReadyState.call(loader);<br />      }<br />

Here we create a callback function on the fly. This function will make a call to the function onReadyState of the ContentLoader (prototype) object that in turns makes a call to the function specified in the onload property of the current ContentLoader object. In both calls, the ContentLoader object is passed as a parameter. Hence, each callback function has access to its own and private request object!

If we load this library in our HTML Document – like this: 

<code></code><p>&lt;script src=&quot;ContentLoader.js&quot; type=&quot;text/javascript&quot;&gt;&lt;/script&gt;&nbsp;</p>

- we can easily create Ajax requests, as many as we like:

function doAjax(url, callback) {<br />  loader = new net.ContentLoader(url,callback);<br />}<br />function startRequests() {<br />  doAjax(&quot;http://technology.amis.nl/blog/postreads.php&quot;, processBlogStats);<br />  doAjax(&quot;empsInDept20.xml&quot;, processEmps);<br />  doAjax(&quot;http://www.oracle.com/technology&quot;, processOTN);<br />}<br />    <br />function processBlogStats() {<br />    alert(&quot;The server replied with the current total Postreads on the AMIS Weblog: &quot; + this.req.responseText);<br />}<br /><br />function el(id) {<br />  return document.getElementById(id);<br />}<br />    <br />function processEmps() {<br />  el('content').innerHTML = this.req.responseText;<br />  el('content').setAttribute(&quot;className&quot;,&quot;visible&quot;);<br />}<br />function processOTN() {<br />  el('content2').innerHTML = this.req.responseText;<br />  el('content2').setAttribute(&quot;className&quot;,&quot;visible&quot;);<br />}<br />&nbsp;

In this example, we do three simultaneous Ajax requests, each with their own callback function, each request neatly encapsulated in its own ContentLoader object.

Repeating Requests for Pollers and Tickers

Sometimes, we use Ajax Requests for checking on a value – and displaying it in our page – that we know will change frequently. Think of counters, stock tickers, weather conditions, news headlines etc. Repetitiveness is not a characteristic of Ajax or Ajax Requests. However, the setTimeOut() system function is integral part of the JavaScript language and that is what we can use to have a request schedule itself again once completed.

I have taken the ContentLoader library we have introduced before and modified it to suit my current needs. I have extended the ContentLoader object, to also contain a property refreshInterval. When set, the request associated with the ContentLoaded object will be scheduled to be re-executed when it has completed. This functionality is found in the last lines of function startProcessing().  Note by the way that this function has some default processing capabilities: if no callback function is specified and if an element is assigned to the ContentLoader, then the Ajax response is pasted either into the value property if that exists (for HTML Form elements like INPUT and TEXTAREA), otherwise the response is pasted into the innerHTML property of the specified element.

This modified version of ContentLoader can deal with Cross Domain requests (see next section) that require a proxy to handle the request from the server side. See the function postLoadSingleResource() for details.

var postLoadResources = new Array();<br />var amis =new Object();<br /><br />amis.STATE_UNINITIALIZED=0;<br />amis.STATE_LOADING=1;<br />amis.STATE_LOADED_AND_PROCESSING=3;<br />amis.STATE_PROCESSED=4;<br />amis.STATE_LOADED_AND_WAITING=5;<br /><br />    function el(id) {<br />      return document.getElementById(id);<br />    }<br /><br /><br />/*--- content loader object for cross-browser requests ---*/<br />amis.PostLoadResource=function           <br />                   ( elementId<br />                   , url<br />                   , requireProxy // boolean indicating whether or not the resource must be acquired through a proxy from a remote domain<br />                   , label<br />                   , processor // function reference of function that will process the resource when received<br />                   , refreshTime // time interval in seconds after which the resource should be reloaded and reprocessed<br />                   ) {<br />  this.elementId=elementId;<br />  this.url=url;<br />  this.requireProxy = requireProxy;<br />  this.state = amis.STATE_UNINITIALIZED;<br />  this.label = label;<br />  this.req = null;<br />  this.id = null;<br />  this.processor= processor;<br />  this.refreshTime = refreshTime;<br />}<br /><br />  // create a new PLR object and add it to the array of PLR objects to be dealt with when the page has loaded<br />  function addPostLoadResource<br />           ( elementId<br />           , url<br />           , requireProxy // boolean indicating whether or not the resource must be acquired through a proxy from a remote domain<br />           , label<br />           , processor // function reference of function that will process the resource when received<br />           , refreshTime // in seconds<br />           ) {<br />     var plr = new amis.PostLoadResource(elementId, url, requireProxy,label, processor, refreshTime);<br />     var size = postLoadResources.push( plr ); // add a new PostLoadResource object to the array<br />     plr.id = size -1; // ensure the plr objects knows where it sits in the postLoadResources array<br />     return plr;<br />  }<br /><br /><br />  function postLoadSingleResource(postLoadResource) {<br />      postLoadResource.state = amis.STATE_LOADING;<br />      if (postLoadResource.requireProxy) {<br />        loader = new net.ContentLoader('proxy?remotehost='+postLoadResource.url, processPostLoad);<br />      }<br />      else {<br />        loader = new net.ContentLoader(postLoadResource.url, processPostLoad);<br />      }<br />      loader.parameter = postLoadResource;<br />  }// postLoadSingleResource<br /><br /><br />  function goPostLoadResources() {<br />    // iterate array postLoadResources<br />    for (i=0;i&lt;postLoadResources.length;i++) {<br />      if (postLoadResources[i].state == amis.STATE_UNINITIALIZED) {<br />        postLoadSingleResource(postLoadResources[i]);<br />      }<br />    }// for<br />  }// goPostLoadResources<br /><br />  // This function is called by the ContentLoader when the AjaxRequest is successfully completed<br />  // and the requested content is available for further processing.<br />  function processPostLoad() {<br />    var postLoadResource = this.parameter;<br />    postLoadResource.req = this.req;<br />    postLoadResource.state = amis.STATE_LOADED_AND_PROCESSING;<br />    startProcessing( postLoadResource);<br />}// processPostLoad<br /><br />  function handleTimeOut(id) {<br />    postLoadSingleResource(postLoadResources[id]);<br

 />  }<br /><br />  // This function is called when a postLoadResources is loaded<br />  // and the requested content is available for further processing.<br />  // There is a number of things we can do in terms of post-processing<br />  // * use the contents as is<br />  // * xslt transform the contents<br />  // * HTML scrape the contents<br />  // * split CSV or otherwise pre-process the results<br />  // taking the result of this first step, we can:<br />  // - paste into the innerHTML of a specified element, for example a DIV or TD<br />  // - copy into the value attribute of a Form element like a TEXTAREA or INPUT<br />  // - process into &lt;OPTION&gt; elements under a select<br />  // - copy into JavaScript memorystructure<br />  // - call custom processor to anything special like populate SVG object<br />  function startProcessing(postLoadResource) {  <br />    if (postLoadResource.processor) <br />    { <br />      postLoadResource.processor.call(postLoadResource);<br />      }<br />    else {<br />      if (postLoadResource.elementId) {<br />        // go find element and load contents<br />        var element = el(postLoadResource.elementId);<br />        if (element.value) {<br />          element.value = postLoadResource.req.responseText;<br />        }<br />        else {<br />          element.innerHTML = postLoadResource.req.responseText;<br />        }<br />      }<br />    }// processor<br />    postLoadResource.state = amis.STATE_PROCESSED;<br />    if (postLoadResource.refreshTime) {<br />      setTimeout(&quot;handleTimeOut('&quot;+postLoadResource.id+&quot;')&quot;, postLoadResource.refreshTime*1000);<br />    }<br />  }// startProcessing<br />&nbsp;

Using this library, we can create repeating Ajax requests as follows:

  &lt;script type=&quot;text/javascript&quot;&gt;<br />  function startRequest() {<br />    addPostLoadResource<br />    ( &quot;postreads&quot;<br />    , &quot;http://technology.amis.nl/blog/postreads.php&quot;<br />    , false // no proxy (note: this will run only in IE for a trusted domain)<br />    , &quot;Get AMIS Blog Total Postreads&quot;<br />    , null // no function reference needed: default handling will paste content in postreads div<br />    , 5 //refreshTime in seconds<br />    );<br />    goPostLoadResources();<br />  }<br />  &lt;/script&gt;<br /><br />

Note: the above script gives problems in IE – though it should not. If I first load the page, it runs okay. When I refresh, it complains about objects to not having been defined. If I empty the browser cache, refresh the page and run again, it is fine again, until the next time I refresh. For Firefox is it running as it should – though not cross browser unless I use the proxy. 

Cross Domain Requests

Browsers try to be quite serious about security. One of the rules most browsers enforce is that a document loaded in the browser cannot make Ajax requests to any other website (domain) than the one the document was loaded from. So if our document loads from our web server, we cannot make an Ajax request to an RSS feed or Web Service just anywhere on the internet. That can be a pity – even though this security thing is of course for our own good.

To deal with this, there are two main routes: one is try to workaround the restrictions in the browsers, using tricks or hacks that are far fetched, not secure or do not feel right. In Firefox for example there is very way to manipulate the security system; however, it is browser specific and does not appeal to me.  The other one is to use a proxy: a generic server side component – can be a servlet, a PHP script or anything really – that receives our requests and turns it into a request of its own to the URL we wanted to access in the first place. When the server side receives the reponse from the remote url, it will simply pass back the content to the browser. So indirectly, we can get content from any remote web site in our Ajax requests. For more details, see the article:Proxy Servlet for AJAX requests to multiple, remote servers

For the purpose of this workshop, we took the easy way and just used Internet Explorer and the work around described below. Therefore, we did not need a proxy servlet to make the remote calls for us.

Working round the cross domain browser issue in Internet Explorer

It is turns out to be deceptively simple to deal with the issue of cross domain requests in Internet Explorer: if you tell IE that the domain that you loaded the base document from – that is: the address or URL you can see in the location-bar of the browser, or at least the first part of it – is a trusted site, you can make all sorts of cross domain (Ajax) requests from JavaScript! To define a domain as a trusted site, go to Tools, Internet Options, pick Security (second tab) and go to Trusted Sites. Click on Sites and type the domain (http://the.domain.com or http://the.domain.com:port) in the Add this Web site to the zone field. Then click Add and presto: you can make Ajax requests from any document you load from the now trusted site to any site anywhere on the internet!


We briefly discussed a number of libraries and frameworks that may aid in doing Ajax style development. The most prominent ones discussed were:

 We also discussed the upcoming changes in JSF 1.2 that hopefully will make integration of Ajax concepts with JSF somewhat easier (possibly allow a subset of components in a view tree to render their response and possible allow for a special non-visual render mode in which components render some sort of structured response (XML?), geared towards contents and not layout/markup).

Books on AJAX

Two very useful books, that we used in preparation for this workshop. The first one is somewhat more fundamental and theoretical, discussing for example a substantial number of Design Patterns and approaching Ajax in quite serious way. This book introduced the basic JavaScript library we have used in the demonstration above. The second book will get you started much sooner. It does not go into very complex and advanced stuff, but to get the hang of Ajax and know where to find more info, I would say it is more than adequate.

Ajax in Action, Dave Crane and Eric Pascarello with Darren James, Manning, October, 2005 | 680 pages, ISBN: 1932394613

Foundations of Ajax, by Ryan Asleson, Nathaniel T. Schutta; APress, October 2005, 296 pages; ISBN: 1-59059-582-3


About Author

Lucas Jellema, active in IT (and with Oracle) since 1994. Oracle ACE Director for Fusion Middleware. Consultant, trainer and instructor on diverse areas including Oracle Database (SQL & PLSQL), Service Oriented Architecture, BPM, ADF, Java in various shapes and forms and many other things. Author of the Oracle Press book: Oracle SOA Suite 11g Handbook. Frequent presenter on conferences such as JavaOne, Oracle OpenWorld, ODTUG Kaleidoscope, Devoxx and OBUG. Presenter for Oracle University Celebrity specials.


  1. I am trying to add a parameter to the handleStateChange() function but it seems to make everything stop working without any errors when I do so…

    Any ideas of how I can pass an elementID to this function???

    I’m trying to update a price field using ajax after users select their product options on this page: http://vision.neteffexstudios.com/hooks.php