edoceo: Latin "to inform fully, instruct thoroughly"

../webpage/int-main/20060513-using-ajax.phtml


Using AJAX

Using AJAX in your web applications yet? Should be, it works very well in most modern user agents such as FireFox, Safari and IE. Microsoft gets credit for first exposing it, other adopted and now everyone can use it. Edoceo is available for consultation and development support on implementing AJAX.

AJAX may seem like a whole new technology with a steep learning curve, it's not. It's simply HTTP requests generated from JavaScript, that's it. It performs GET with querystring parameters, POST with with form encoded data or XML or arbitrary data. The response can be XML, HTML, JavsScript or whatever the developer chooses. The concept really is that simple, send and recieve any type of HTTP request.

Basic AJAX Request

To start a generic request function is defined,ajax_request(url,post,type,event_handler), which will be used to perform all requests. It's the core of this AJAX implementation. It sends the request to the url, gets the response and returns the full content. If post is supplied it will be sent to the server as x-www-form-urlencoded data. Specificy a type of text/xml to specify that the post data is XML; the response will be assumed to be XML. If event_handler is defined it will be set as the callback routine and the request will become asynchronous. All browsers only allow the request to go to the server/domain that originated the page.

// note: where is the error checking?
function ajax_request(url,post,type)
{
  ua = null;
  if (window.XMLHttpRequest) { ua = new XMLHttpRequest(); } // {Mozilla,Safari}
  else if (window.ActiveXObject) // IE
  {
    try { ua = new ActiveXObject('Msxml2.XMLHTTP'); }
    catch (e)
    {
      try { ua = new ActiveXObject('Microsoft.XMLHTTP'); } 
      catch (e) {}
    }
  }
  if (!ua) { alert('AJAX not available!'); return false; }
  
  if (post)
  {
    if (!type) type='application/x-www-form-urlencoded';
    // Assume XML response if sending XML
    if ((type='text/xml') && (ua.overrideMimeType)) ua.overrideMimeType('text/xml');
    ua.open('POST', url, false);
    ua.setRequestHeader('Content-Type', type);
    ua.setRequestHeader('Content-Length', post.length);
    ua.send(post);
  }
  else
  {
    ua.open('GET', url, false);
    ua.send(null);
  }
  if (type=='text/xml') return ua.responseXML;
  return ua.responseText;
}

Very Simple AJAX

This example uses AJAX to redraw a specific element on the page. It works like this:

  1. Some user action results in a call to the function redraw_element(id,url).
  2. redraw_element requests url and replaces the contents of the identified element with the response.

It's a very simple two step process, here's the code for redraw_element.

// note: where is the error checking?
function redraw_element(id,url)
{
  e = document.getElementById(id);
  if (!e) { alert('redraw_element: cannot find: ' + id); return false; }
  e.innerHTML = ua_request(url);
}

This example here submits a form, ignoring submit type elements. It works like this:

  1. Some user action results in a call to the function submit_form(id,url).
  2. redraw_element requests url and replaces the contents of the identified element with the response.

It's a very simple two step process, here's the code for redraw_element.

function submit_form(id,cmd)
{
  f = document.getElementById(id);
  if (!f) return false;

  buf = '';
  for (i=0;i<f.elements.length;i++)
  {
    e = f.elements[i];
    alert(e.type);
    // Ignore the Command buttons, using whats specified above
    if (e.name!='cmd') buf+= e.name + '=' + encodeURI(e.value) + '&';
  }
  buf+= 'cmd=' + encodeURI(cmd);
  return ajax_request(f.action,buf);
}

Using this AJAX Template

To use this template in some web application follow along here.

  1. Create a main display page, say a client with a list of invoices.
  2. Create a page to receive POSTed data.
  3. Create a page that will be called by the AJAX routines that returns HTML.

Below are snips of pages that operate like this

<!-- edit.html -->
<div id='edit_form'></div>
<div id='invoice_list'></div>
<input onclick="submit_form('some_form','cmd=Save');" />

<script type='text/javascript'>
redraw_element('edit_form','./draw.php?id=1&what=edit_form');
</script>

// draw.php
// code here to handle input and return HTML
echo "<p>This response comes from draw.php</p>

// post.php
// code here to handle posted data
if ($_GET['id'])
{
  // maybe load Client object and manipulate it accordingly
  exit("true");
}

When the user loads edit.php it will draw a few div tags then execute the redraw_element function. redraw_element will make a request to draw.php with the required parameters. draw.php writes out the required HTML which redraw_element uses to replace the current contents. Provided everything works smoothly the content will be instantly updated.

Form submission works in a very similar fashion. Create button or somesuch that onclick calls submit_form with the necessary parameters. The forms input elements, except submits are encoded into POST type data and then passed to ajax_request. post.php should write back a value that would be understood to be a success or failure message.

It should be obvious that the above samples have limited error handling. To provide a rich user experience this functionality should be added.

Conclusion

AJAX is simple and reliable in modern browsers. Implementing this technology can be done in a gradual fashion. Starting with something simple like the above to redraw elements and POST data. With the proper handlers written AJAX can also be used in place of IFRAMES to render framed like content. Advanced AJAX allows for incredibly complicated logic and datasets to be exchanged, asynchronously!

See Also

ChangeLog

XHTML 1.1. and CSS2.1/3 © 1999-2008 Edoceo, Inc.
Edit this Page