Simple ajax stuff - asynchronously getting and displaying data from a server using the DOM API

  toucheatout  2006-07-15 17:06  Web   Asynchronous transactions is what the regular web is not about. That is, communication with the server of partial information. The page is systematically and fully transmitted to the client. Next request will also be for a complete document, which is unefficient when all you want is updating a single item on the page in reaction of user action. More reactive an interface, more rational with bandwidth... That is more liberty for the developers Tadatin! Here comes AJAX... Here's a simple example on how to fill a div with the server requested date using AJAX:

The Files and their organization

I chose to separate the javascript code in distinct files to make things clearer:
  1. include/ajax-common.js, the generic AJAX XMLHttpRequest object creation:
    var http_request = false; function createXMLRequest(){ if (window.XMLHttpRequest) { // Mozilla, Safari,... http_request = new XMLHttpRequest(); if (http_request.overrideMimeType){http_request.overrideMimeType('text/xml');} } else if (window.ActiveXObject) { // IE try {http_request = new ActiveXObject("Msxml2.XMLHTTP");} catch (e) { try { http_request = new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) {} } } if (!http_request) {alert('Cannot create XMLHTTP instance'); return false; } return http_request; } function makeGETXMLRequest(url, parameters, callback) { http_request = createXMLRequest(); http_request.onreadystatechange = callback;//Callback for when status changes http_request.open('GET', url + parameters, true); http_request.send(null); }
  2. include/ajax.js, the page-specific function requesting asynchronous information and rendering it - here gets from xml.php an information and displays it in the page, within the element with aText id:
    function myCallback() { if (http_request.readyState == 4) {//--> 0 uninitialized 1 loading 2 loaded 3 interactive 4 complete if (http_request.status == 200) { var xmldoc = http_request.responseXML; var text_content = xmldoc.getElementsByTagName("text")[0].childNodes[0].nodeValue; document.getElementById("aText").innerHTML = text_content; alert('Full XML: \n'+ http_request.responseText); } else { alert('There was a problem with the request. Status: ' + http_request.status + ' Readystate: ' + http_request.readyState); } }// else on readyState } function myAction() { makeGETXMLRequest('xml.php', '?test=2', myCallback); }
  3. For GET requests, an URL - xml.php in the current directory for this example. It goes by a php bit, just by principle :) One can choose a static xml, for the simplest purposes, yet it comes quite obvious that real power will be drawn from dynamic, database driven generation, XML-formatted by need: Hello World at
  4. HTML code to glue things together: ... ... ...
    Here comes the thing!
    ...
    Note that another element than a div could have been used...

Summing up the participants

In this simple usage of AJAX, there are clear-cut parts of the mechanism that have been isolated:
  1. The common javascript functions creating and doing the asynchronous requests.
  2. The javascript functions defining the request concretely to be made and the changes to apply, in reaction to a specific event.
  3. The callback functions, doing the job with the result. Tightly coupled with the above, as the are individually associated when doing/sending the request.
  4. The HTML code invoking the javascript, and providing the elements so that the afferent javascript execution is successful.
Very nice, more extensive resources at Captain.at AJAX tutorials or the mozilla.org developer's "Getting Started". Yet in the meantime,
 
Informatics


yro.slashdot.org - Your Rights online


nytimes.com New York Times - International


Informatic headlines