AJAX The Little Useful Engine – The First Example

This is an example html file showing how AJAX works. The server side has a php file to respond to the AJAX request from the html page. The content of the php file is pasted at the bottom of this html file as comments.

<html><head>
  <script language=javascript type='text/javascript'>
  /*see code.google.com/edu/ajax/tutorials/ajax-tutorial.html */
  var obj; var prompt = true;
  function ProcessXML() {
    var loc = document.location;
    var url = loc.protocol + '//' + loc.host + '/ajaxtest/getdate.php';
    url += '?rand=' + parseInt(Math.random()*999999999999);
    // native  object
    if (window.XMLHttpRequest) {
      obj = new XMLHttpRequest();
      obj.onreadystatechange = processChange;
      obj.open("GET", url, true); // "true" for asynch
      obj.send(null);// null for GET, string for POST
    } else if (window.ActiveXObject) {// IE/Windows ActiveX object
      obj = new ActiveXObject("Microsoft.XMLHTTP");
      if (obj) {
        obj.onreadystatechange = processChange;
        obj.open("GET", url, true);
        obj.send();// don't send null for ActiveX
      }
    } else {
      alert("Your browser does not support AJAX");
    }
  }
  function processChange() {
      // 4 means the response has been returned and ready to be processed
      if (obj.readyState == 4) {
        if (obj.status == 200) {// 200 means "OK"
          if (prompt) {
            document.getElementById('ajaxprompt').innerHTML += ' good <br />';
            prompt = false;
          }
          document.getElementById('ajaxdate').innerHTML =
                obj.responseXML.getElementsByTagName("timenow")[0]
                   .childNodes[0].nodeValue;
          document.getElementById('ajaxtext').innerHTML = obj.responseText;
          setTimeout( function(){ProcessXML();}, 1000 );
        } else {
            alert("There was a problem in the returned data:\n");
        }
      }
      if (prompt) {
        document.getElementById('ajaxprompt').innerHTML +=
                ' ' + obj.readyState + ' ' + obj.status + ' <br />';
        document.getElementsByTagName('p')[1].childNodes[0].nodeValue =
	        document.getElementById('ajaxprompt').innerHTML;
      }
  }
  </script>

</head> <body onload='ProcessXML()'>
  <table border='3' padding='3'>
    <tr><th>Ajax Test Prompt and Date<th></tr>
    <tr><td><div id='ajaxprompt'></div></td></tr>
    <tr><td><div id='ajaxdate'></div></td></tr>
  </table>
<p> A Normal Paragraph </p>
<p> </p>
<p id='ajaxtext'></p>
</body></html>
<!--
put this into ajaxtest/getdate.php:
<?php header('Content-Type: text/xml');
      date_default_timezone_set('UTC');
      echo "<?xml version=\"1.0\" ?><clock><timenow>"
           .date('H:i:s')."</timenow></clock>";
?>
-->

The url suffix “?rand=12345” is for always using a new URL so to bypass the cache. Alternatively one can call “obj.setRequestHeader('Cache-Control:', 'must-revalidate')” or use “obj.setRequestHeader('Pragma:', 'no-cache')“, but those may not work properly on some browsers.

Framework note: Take a look at prototype.js and rico.js, they help improve the programming productivity.

Advertisements

About minghuasweblog

a long time coder
This entry was posted in AJAX and Webapp, All and tagged , , , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s