How to Perform AJAX Tasks with JavaScript - dummies

How to Perform AJAX Tasks with JavaScript

By John Paul Mueller

Using AJAX with pure JavaScript is a two-part process. First, you must send the request. Second, you must process the response. The following code shows the two parts of the process used to change just part of a page. You must execute this code on your server — it won’t respond properly from the local drive.

// Create a connection to the server.
var Connect = new XMLHttpRequest();
function LoadDoc()
  // Specify which function to use on return.
  Connect.onreadystatechange = ProcessData;
  // Make the request."GET","Special.txt",true);
function ProcessData()
  // Verify the return status.
  if ((Connect.readyState == 4) &&
    (Connect.status == 200))
   // Modify the <div> content.
   document.getElementById("ChangeText").innerHTML =

The code begins by creating an XMLHttpRequest object, Connect, which is used to handle the connection with the server. This object is common to both requesting the data and processing it later.

When a user clicks Change the Text, the button calls LoadDoc(). The first step is to tell Connect where to find the function, ProcessData(), used to process the data later. The code then creates a request for Special.txt using the GET method. Notice that the open() function is set to use an asynchronous call rather than a synchronous call, which you might use when working with XML data.

The ProcessData() function receives input any time that the readyState changes for the connection. However, you don’t need to process every change. The code begins by checking for a readyState of 4 and a status of 200, which means that the response has been successfully processed and is ready to use. When this combination occurs, the code changes just the text of the target <div> onscreen.