Ajax Basics

Introduction

This page covers the basics of setting up a web page to use Ajax. Ajax stands for Asynchronous JavaScript with XML and really refers to a style of web page development. Instead of the standard request and response cycle of a regular web page, requests are made using JavaScript in the browser. The script then handles making the request for data and formatting the response.

The examples covered here are a summary of the techniques covered in two very excellent books. Please refer to them if you need more information on the subject.

Bulletproof Ajax PPK on JavaScript

Getting a Text File with Ajax

For the first example, a simple text file is retrieved using Ajax.

AjaxHello.html (Sample)
AjaxHello.html (Source)

   1:<html>
   2:<head>
   3:    <title>Ajax Hello!</title>
   4:    <!-- Get Javascript code-->
   5:    <script type="text/javascript">
   6:
   7:function getHttpObject(){
   8:    var httpObject = false;
   9:    if (window.XMLHttpRequest){
  10:        httpObject = new XMLHttpRequest();
  11:    } else if (window.ActiveXObject){
  12:        try{
  13:            httpObject = new ActiveXObject("Msxml2.XMLHTTP");
  14:        } catch(e) {
  15:            try {
  16:                httpObject = new ActiveXObject("Microsoft.XMLHTTP");
  17:            } catch(e) {
  18:                httpObject = false;
  19:            }
  20:        }
  21:        
  22:    }
  23:    return httpObject;
  24:}
  25:
  26:function getMsg(){
  27:    var request = getHttpObject();
  28:    if (request){
  29:        request.onreadystatechange = function(){
  30:            handleRequest(request);
  31:        }
  32:    }
  33:    request.open("GET", "msg.txt", true);
  34:    request.send(null);
  35:}
  36:
  37:
  38:function handleRequest(request){
  39:    if (request){
  40:        if (request.readyState == 4){
  41:            if (request.status == 200 || request.status == 304){
  42:                updateText(request.responseText);
  43:            }
  44:        }
  45:    }
  46:}
  47:
  48:
  49:function updateText(newText){
  50:    var paraRef = getIdHandle("msgPara");
  51:    paraRef.innerHTML = newText;    
  52:}
  53:
  54:
  55:
  56:// Get Hand to an element by Id
  57:function getIdHandle(tagName){
  58:    return document.getElementById(tagName);
  59:}
  60:
  61:// Assign Handlers to Page Load
  62:
  63:function load(){
  64:    //alert("load called");
  65:    var ref = getIdHandle("getMsgId");
  66:    ref.onclick = getMsg;
  67:}
  68:
  69:// Page loader
  70:window.onload = load;
  71:    </script>
  72:</head>
  73:<body>
  74:    <h2>Ajax Hello!</h2>
  75:    <p>This page loads a message from a text file on the server using Ajax.</p>
  76:    <h3>Additions</h3>
  77:    <p><a href="#" id="getMsgId"><b>Get Message</b></a></p>
  78:    <h4>Message is</h4>
  79:    <p id="msgPara">
  80:    </p>
  81:</body>
  82:</html>

A quick review of the important parts of the example is in order.

That covers the hightlights.

Retrieving a Date with Ajax

Why don't not try something a little more useful? The following example extends the previous example a little bit. Instead of reading from a file, a PHP script is called with returns the current date and time. This can be called and inserted in the page. Each time the user clicks on the link, the date is updated on the page without any refresh.

AjaxDate.html (Sample)
AjaxDate.html (Source)

   1:<html>
   2:<head>
   3:    <title>Get Date</title>
   4:    <!-- Get Javascript code-->
   5:    <script type="text/javascript">
   6:
   7:function getHttpObject(){
   8:    var httpObject = false;
   9:    if (window.XMLHttpRequest){
  10:        httpObject = new XMLHttpRequest();
  11:    } else if (window.ActiveXObject){
  12:        try{
  13:            httpObject = new ActiveXObject("Msxml2.XMLHTTP");
  14:        } catch(e) {
  15:            try {
  16:                httpObject = new ActiveXObject("Microsoft.XMLHTTP");
  17:            } catch(e) {
  18:                httpObject = false;
  19:            }
  20:        }
  21:        
  22:    }
  23:    return httpObject;
  24:}
  25:
  26:function getDate(){
  27:    var request = getHttpObject();
  28:    if (request){
  29:        request.onreadystatechange = function(){
  30:            handleRequest(request);
  31:        }
  32:    }
  33:    request.open("GET", "getdate-text.php", true);
  34:    request.send(null);
  35:}
  36:
  37:
  38:function handleRequest(request){
  39:    if (request){
  40:        if (request.readyState == 4){
  41:            if (request.status == 200 || request.status == 304){
  42:                updateText(request.responseText);
  43:            }
  44:        }
  45:    }
  46:}
  47:
  48:
  49:function updateText(newText){
  50:    var dateParaRef = getIdHandle("datePara");
  51:    dateParaRef.innerHTML = newText;    
  52:}
  53:
  54:
  55:
  56:// Get Hand to an element by Id
  57:function getIdHandle(tagName){
  58:    return document.getElementById(tagName);
  59:}
  60:
  61:// Assign Handlers to Page Load
  62:
  63:function load(){
  64:    //alert("load called");
  65:    var linkRef = getIdHandle("getDateLink");
  66:    linkRef.onclick = getDate;
  67:}
  68:
  69:// Page loader
  70:window.onload = load;    
  71:    </script>
  72:</head>
  73:<body>
  74:    <h2>Show Date</h2>
  75:    <p>This page loads a the text date from a PHP script via Ajax.</p>
  76:    <h3>Additions</h3>
  77:    <a href="#" id="getDateLink">Get Date</a>
  78:    <h4>Today's Date is</h4>
  79:    <p id="datePara">
  80:    </p>
  81:</body>
  82:</html>

Note much has changed from the first example. Line 33 calls an actual PHP script instead of a text file. The PHP script generates the date.

Here is the source code for the PHP script used to generate the date.

getdate-text.php (Source)

   1:<?php
   2:    # Return Date and time as decimals
   3:    print ("<p>" . strftime('%m/%d/%y %H:%M:%S') . "</p>");
   4:?>

That completes this quick overview of an Ajax page. See the books linked above for more information on the subject.