a developer's notes – a semi-technical web development BLOG

September 2, 2011

A Sample AJAX Script

Filed under: Javascript / JQuery — Duy Nguyen @ 2:51 am
Tags: , , , ,

Here is a sample AJax application. This was taken from “Ajax for Dummies”.

Here a user clicks on the “Display Message” button and it retrieves text from a text file and changes the text on the web page.

The application:

Here is the code:

<script language = “javascript”>

//Create the XMLHttpRequest object
var XMLHttpRequestObject = false;
if (window.XMLHttpRequest) {
    XMLHttpRequestObject = new XMLHttpRequest();
else if (window.ActiveXObject) { //For Internet Explorer only
    XMLHttpRequestObject = new ActiveXObject(“Microsoft.XMLHTTP”);
//a function that takes a path for the datasource location and the div's ID to put the retrieved data into
function getData(dataSource, divID){
    if(XMLHttpRequestObject) {

        //find the div to put the data into
        var obj = document.getElementById(divID);

        //open(“method”, “URL”[, asyncFlag[, “userName”[, “password”]]])
        XMLHttpRequestObject.open(“GET”, dataSource); 

        //Set up the anonymous function to call when ready. The actual request isn't until later
        XMLHttpRequestObject.onreadystatechange = function() 
            //readState[ 0:uninitialize, 1:loading, 2:loaded, 3:interactive, 4:complete ]
            //status 200 = OK
            if (XMLHttpRequestObject.readyState == 4 && XMLHttpRequestObject.status == 200) {
                //data retrieved sucessfully so put the retrieved data into the div
                obj.innerHTML = XMLHttpRequestObject.responseText;
        //request server for data. And the anonymous function will handle the response back from the server
        XMLHttpRequestObject.send(null); //null is only used for GETs

<H1>Fetching data with Ajax</H1>
        <input type = 'button' value = 'Display Message' onclick = 'getData(‘http://localhost/ch01/data.txt’,‘targetDiv’)'>
    <div id='targetDiv'>
        <p>The fetched data will go here.</p>

The text file data.txt, contains:

This text was fetched using Ajax.

I hope this was simple enough. The interesting thing about this is that the function to handle the response is setup before the actual request call. Enjoy!

1 Comment »

  1. That was cool. Thanks for the great comments!

    Comment by Tony — September 2, 2011 @ 4:18 am | Reply

RSS feed for comments on this post. TrackBack URI

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 )

Google photo

You are commenting using your Google 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 )

Connecting to %s

Create a free website or blog at WordPress.com.

%d bloggers like this: