Tutorial Menu

Basic AJAX - Calling the AJAX class

The class defined in the previous example can be called but first of all the framework for the AJAX application must be set up.

The following files will be needed:

AJAX1.html is a standard xHTML page with the following structure

<!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" xml:lang="en" lang="en">
    <head>
        <title>My First AJAX  Call</title>
        <script type="text/javascript" src="AJAXClass.js"></script>
    </head>
    <body>
        <div id="load" style="display:none;">The data is loading</div>
        <h1>My First AJAX call</h1>
        <p><a href="javascript:makeCall()">Make Call</a></p>
        <p><span id="dataTarget"></span></p>
    </body>
</html>

The page has three elements: a loading message that is originally hidden, a link to make the call and a span to place the data from the request.

In order to make this page functional we must add the makeCall function in the header below the current script tags.

<script  type="text/javascript">
    function makeCall(){
        var myAJAX= new AJAXClient();
        myAJAX.isAsync=true;
        myAJAX.callback= function(result){
              document.getElementById('dataTarget').appendChild(
                   document.createTextNode(myAJAX.xmlhttp.responseText));
       
        }
        myAJAX.makeRequest('Data.txt', null);
    }
</script>

The function makeCall creates a new AJAX client and defines a function to handle the call back. In this case it updates the span dataTarget with the text in Data.txt.

The make call function then calls the makeRequest initialising the httpRequest and the class handles any errors.

See example (opens in new window).

Data.txt can hold any information, including html hat you want to display.

This basic example is not accessible for people without JavaScript or running JavaScript with a screen reader. To do this the Class must be modified to update the user to where the page has been updated and a noscript alternative must be given.

Previous: Basic AJAX - Creating an AJAX class Next: Basic AJAX - Making the AJAX class more accessible

References

Eichorn, J. (2006). Understanding AJAX. Upper Saddle River, NJ: Pearson Education, Inc.

Zakas, N. C. (2005). Proffessional JavaScript for web developers. Indianapolis: Wiley Publishing Inc.