AJAX Examples

XMLHttpRequest: the Heart of AJAX

var req = new XMLHttpRequest ();
req.open ('GET', 'http://www.mozilla.org/', true);

req.onreadystatechange = function (aEvt) {
    if (req.readyState == 4) {
        if (req.status == 200)
            dump (req.responseText);
        else
            alert ("Error loading page");
    }
};

req.send(null);

Web 2.0

The "old web" used static HTML (or at least static content with JavaScript) that only changed if the people hosting the site changed it. AJAX has since enabled sites to be user-modifiable. Wikipedia is an excellent example of Web 2.0-ish user-generated content.

Making Web 2.0 applications with AJAX is simple in theory. JavaScript is used to update the database and reflect changes to other users dynamically. For example, you can use the following JavaScript to send a message to an online message board via XML-RPC:

function post (msg)
{
    var req = new XMLHttpRequest ();
    req.open ('POST', 'http://virtual0.cs.missouri.edu:8004');

    req.onreadystatechange = function (aEvt) {
        if (req.readyState == 4) {
            if (req.status != 200) {
                alert ("error talking to RPC server");
            }
        }
    };

    var xmlrpcrequest = "<?xml version='1.0'?>" +
                        "<methodCall><methodName>setMessage</methodName>" +
                        "<params><param><value><string>" + msg +
                        "</string></value></param></params></methodCall>";

    req.send (xmlrpcrequest);
}

... and the following function to display the current message:

function refresh () {
    var req = new XMLHttpRequest ();
    req.open ('POST', 'http://virtual0.cs.missouri.edu:8004');
    var msgcontainer = document.getElementById ('msgcontainer');

    req.onreadystatechange = function (aEvt) {
        if (req.readyState == 4) {
            if (req.status == 200) {
                msgcontainer.innerHTML = req.responseXML.documentElement.getElementsByTagName ('string') [0].childNodes [0].nodeValue;
            }
            else {
                alert ("error talking to RPC server");
            }
        }
    };

    var xmlrpcrequest = "<?xml version='1.0'?>" +
                        "<methodCall><methodName>getMessage</methodName>" +
                        "<params></params></methodCall>";

    req.send (xmlrpcrequest);
}

A simple web page to show the current message might have a body like this:

<body onLoad="refresh();">  <div id="msgcontainer"></div> </body>

Notice that this logic was implemented without any PHP or CGI.  It is all done in the browser. In particular, there is no server-side processing involved in rendering the page.  The server only provides the information required to render the page.  This is much better for several reasons:

  • there is a logical separation between the data and the rendering logic
  • lets your browser do what it was designed to do: render pages
  • your server doesn't need to load, interpret, and execute CGI scripts
  • your server spends a lot less time processing; instead your clients do most of the work

You can use the hybrid XML-RPC/HTTP server from Project 3 to host this message board.  Just implement the proper RPC methods:

class RPCMethods :

    
message = "Nothing here yet..."

    def setMessage (self, new_message) :
        self.message = new_message
        return True

    def getMessage (self) :
        return self.message

Obviously this simple server back-end could be extended with some persistence mechanism; for example, the message could be saved/restored using an sqlite3 database.

AJAX with REST APIs

You can use AJAX to grab information from a REST API on your server:

function search(query) {
  var req = new XMLHttpRequest (); 
  req.open ('GET', '/search.php?q=' + escape(query), true); 

  req.onreadystatechange = function (aEvt) {
    if (req.readyState == 4) { 
        if (req.status == 200) 
            showResults(JSON.parse(req.responseText));
        else 
            alert ("Error talking to REST API page"); 
    }
  };

  req.send(null);
}

Loading External JavaScript

It is possible for your page to load JavaScript in separate files, either from your server or from another server.  This has the following benefits:

  • your pages can be better organized into separate JavaScript and HTML components
  • rather than cut-and-pasting common JavaScript functions to several pages, you can have several pages load an external JavaScript file
  • you can borrow JavaScript from other sites; ex. Google Maps publishes JavaScript you can use to display maps in your pages
There are a few ways to do this:

Static HTML Way

If your web page is static (or generated server-side) you can use the <script> tag and specify a src attribute:

<script language="javascript" src="http://example.com/external.js"></script>

The Dynamic HTML Way

If you want to load JavaScript dynamically, you can append a new <script> tag to the DOM:

var e = document.createElement("script");
e.src = "http://example.com/external.js";
e.type="text/javascript";
document.getElementsByTagName("head")[0].appendChild(e); 

This code must be run after the <head> node is loaded (or else the code won't be able to find the head!), so you can't execute this code within a <script> tag within the <head>.  Instead, wrap the above in a function and call it after the document is loaded using the onload event:

<body onLoad="loadExternalJavaScript();">...

The AJAX Way

It is also possible to use XMLHttpRequest to load JavaScript.  However, this method is subject to the Same Origin Policy, so you can only load JavaScript from your own server.

Using a REST API

This page grabs information from flickr.com using JSONP:

<html>
<head>
<script language="javascript">
function jsonFlickrApi (json) {

        
alert ('called jsonFlickrApi callback');

document.write (json.photos.photo.length);

for (var i = 0; i < json.photos.photo.length; ++i) {

var photo = json.photos.photo [i];
var url = "http://farm" + photo.farm 
+ ".static.flickr.com/" 
         + photo.server + "/" 
         + photo.id + "_" 
+ photo.secret + "_m.jpg";

document.write ("<img src='" + url + "'>");
}
}
</script>
<script language="javascript" src="http://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=cd3cd130c745c46d758110588a50176a&tags=dog&format=json"></script>
</head>
<body>
</body>
</html>

Comments