How to Use IrfanView’s Built-In Effects for HTML5 and CSS3 Programming
How to Create a New JavaScript File in Komodo Edit
How to Create Cascading Style Sheets (CSS) Simply and Easily

How to Perform AJAX Tasks with JavaScript

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.
  Connect.open("GET","Special.txt",true);
  Connect.send();
}
function ProcessData()
{
  // Verify the return status.
  if ((Connect.readyState == 4) &&
    (Connect.status == 200))
  {
   // Modify the <div> content.
   document.getElementById("ChangeText").innerHTML =
     Connect.responseText;
  }
}

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.

  • Add a Comment
  • Print
  • Share
blog comments powered by Disqus
10 Stellar Web Resources for HTML5 and CSS3
How to Register a Domain Name for Your HTML5 and CSS3 Site
Using Templates with PHP
How to Create a Mail Pilot in Your HTML5 Game
How to Use JavaScript’s continue Statement
Advertisement

Inside Dummies.com