AJAX is a web-buzzword that I had always thought must be more complicated than it really is. I finally got a chance to look into it and write up a simple example. The example

example.html

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>AJAX example</title>
<script type="text/javascript">
var httpObject = getHTTPObject();

function getWord() {
  return document.getElementById('word').value;
}
function setDef(text) {
  /* HTML way */
  /* document.getElementById('def').innerHTML = text; */
  /* XHTML way */
  var text_node = document.createTextNode(text);
  var p = document.getElementById('def');
  p.replaceChild(text_node, p.childNodes[0]);
}
function getHTTPObject() {
  if (window.ActiveXObject)
    return new ActiveXObject("Microsoft.XMLHTTP");
  else if (window.XMLHttpRequest)
    return new XMLHttpRequest();
  else {
    setDef("Your browser does not support AJAX.");
    return NULL;
  }
}
function doAJAX() {
  if (httpObject != null) {
    httpObject.open("GET", "lookup.php?word=" + getWord(), true);
    httpObject.send(null); /* request is on it's way... */
    setDef("Sent request for " + getWord());
    /* here's the asynchronous read: */
    httpObject.onreadystatechange = function() { respondAJAX(); }
  }
}
function respondAJAX(){
  if(httpObject.readyState == 4) {
    var $xml = httpObject.responseXML;
    var $text = $xml.getElementsByTagName('result')[0].childNodes[0].nodeValue;
    setDef($text);
  }
}
</script>
</head>
<body>
  <form action="never_call_this_invalid_page.html" method="get">
    <p>
      Word: <input type="text" name="word" id="word" onblur="doAJAX();"/><br />
      Click somewhere else to lookup word.
    </p>
    <p id="def"> </p>
  </form>
</body>
</html>

Posted

accesses the server-side

data.xml

<?xml version="1.0" encoding="UTF-8" ?> 
<dictionary>
  <entry>
    <word>ping</word>
    <definition>A common dummy word for testing functionality.</definition>
  </entry>
  <entry>
    <word>dummy</word>
    <definition>One word seemed too silly...</definition>
  </entry>
</dictionary>

Posted

via

lookup.php

<?php
// generate an xml snippet with the requested information.
// stays server-side.

$word = $_GET['word'];

$ret = '';

$f = simplexml_load_file('data.xml');
foreach ($f as $entry) {
  if ($entry->word == $word) {
    $ret .= '<result>'.$entry->definition.'</result>';
    // this doesn't even have to be XML, but we're doing official "AJAX"
    break;
  }
}
if (strlen($ret) == 0) {
  $ret .= '<result>'.$word.' not found</result>';
}

header("Content-Type: text/xml; charset=UTF-8");
echo '<'.'?xml version="1.0" encoding="UTF-8" ?'.">\n";
echo $ret;

?>

Posted