http://berndartmueller.at/wp-content/themes/HashOne
http://berndartmueller.at
Obox Signature Series Subscribe to my RSS feed

2 Comments Tutorial: How to make your first ajax request

Article written by the brilliant Bernd on the 18 Apr 2009

Today I want to show you a little tutorial to make your first ajax request. In this tutorial I’ll make a request to the server and try to get the ajax.txt file. This is the first step to start ajax developing to improve the usability and accessibility of your website. At the end of the tutorial you can also download the files and experiment with them.

So, let’s start.

Step 1

First we create a html markup like this one.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>First Ajax Request</title>

</head>

<body>
<a href="test.txt">Get File</a>
</body>
</html>

Later, when we click on the “Get File” link, the file should be loaded into the browser.

Step 2

Next we have to import our javascript file.

<script type="text/javascript" src="ajax.js"></script>

Then we also add a click event handler on the link.

<a href="test.txt" onclick="getFile(this.href); return false;">Get File</a>

Whenever the user clicks on that link, the method “getFile” get called with a parameter, which represents the path to the file we want to load. The “return false” is required, if the browser successfully loaded the file, to deactivate the link and the browser doesn’t redirect us.

Step 3

Now create the file which you want to load in the browser, eg. text.txt and write something in it like “Hello World!”

Step 4

Create a new file and call it “ajax.js”. This will contain our functios for the request. First we’ll write a function to get the XMLHttp object. Start with creating a new instance of an XMLHttpRequest object

var xhr = new XMLHttpRequest();

But it isn’t that simple in Internet Explorer. There you need to create a new instance of an ActiveX object.

var xhr = new ActiveXObject("Microsoft.XMLHTTP");

Before creating the new instance, we have to test for the exisctence of the object.

if (window.XMLHttpRequest){
  xhr = new XMLHttpRequest();
}
else if (window.ActiveXObject) {
  try {
    xhr = new ActiveXObject("Msxml2.XMLHTTP");
  }
  catch(e) {
    try {
      xhr = new ActiveXObject("Microsoft.XMLHTTP");
    } catch(e) {
      xhr = false;
    }
  }
}

Last we return the xhr object. Then the final function should look like this.

function getHTTPObject(){
  var xhr = false;

  if (window.XMLHttpRequest){
    xhr = new XMLHttpRequest();
  }
  else if (window.ActiveXObject) {
    try {
      xhr = new ActiveXObject("Msxml2.XMLHTTP");
    }
    catch(e) {
      try {
         xhr = new ActiveXObject("Microsoft.XMLHTTP");
      } catch(e) {
        xhr = false;
      }
    }
  }
  return xhr;
}

Step 5

The next step is to send the request and receive the file. So we write a function “getFile” with one parameter, which expects the path of the file we want to load in the browser. Then we create the first time a instance of the XMLHttpObject.

function getFile(file){
  var request = getHTTPObject();
}

The getHTTPObject function could has returned a value of false, which means that the browser does not have Ajax capabilities. So we have to check this with an easy if condition.

if (request){
  //Do some Ajax
}

Now we have created an instance of XMLHttpRequest and we are ready to send a request to the server.

Step 6

To do this, there are three components.

1. The onreadystatechange event handler
2. The open method
3. The send method

ONREADYSTATECHANGE

This is an event that is triggered by the server, not by the user. During an Ajax operation, the server sends updates to the client about the current status of the communication. This is done by updating a property of the XMLHttpRequest object. It’s called readyState. Every time the readyState property is changed, the readystatechange event is triggered. If you register a function to this event handler, the function will be executed every time the server pings the client with an update.

if (request){
  request.onreadystatechange = DoSomething;
}

In the next step, we have to specify the details of the Ajax request.

Step 7

To specify the details of the Ajax request, such as the url of the file you want to request, “GET” or “POST” and a boolean which indicated whether the request should occour asynchronously or not. For our example we use “GET” and true, because we want an asynchronous request.

function getFile(file){
  var request = getHTTPObject();

  if (request){
    request.onreadystatechange = DoSomething;
    request.open("GET", file, true);
    request.send(null);
  }
}

Step 8

Now we have a succesfull request, the only thing we have to do now, is to receive the response and display it. We can do this, with checking two propertys.

READYSTATE

It indicates the current state of an Ajax request.

0 Uninitialized. The open methond hasn’t been called yet.
1 Loading. The open method has been called, but the send method hasn’t.
2 Loaded. The send method has been called. The request has started.
3 Interactive. The server is in the process of sending a response.
4 Complete. The server has finished sending a response.

So we have to check the status of this object and wait until it’s value reached 4.

function displayResponse(request){
  if (request.readyState == 4){
    //Do something with the response
  }
}

The other property we have to check now it the status property. It’s a three-digit numerical value. The most common status code is 200, which means “OK”. Other codes are 403 for “forbidden”, 404 for “Not Found” and 500 for “Internal Server Error”. By comparing this property to a value of 200, you can be sure that the server has sent a successful response.

if (request.readyState == 4){
  if (request.status == 200 || request.status == 304){
    //Display the response
  }
}

The last thing is to display the received response in the browser and register this function to the onreadystatechange property.

var node = document.createElement("p");
var text = document.createTextNode(request.responseText);
node.appendChild(text);
document.getElementsByTagName("a")[0].parentNode.insertBefore(node, document.getElementsByTagName("a")[0]);

The request.responseText property contains the data sent from the server. Depending on what the server is sending, this might be a string of HTML, XML or just a string of text.

And now register this function to the onreadystatechange property.

request.onreadystatechange = function(){ displayResponse(request) };

That’s it. It’s the basic of Ajax and now you are able to learn more details of Ajax and how to improve Usability with Ajax.

Download source files

2 Comments Subscribe to these comments.

August 19, 2010 4:49 pm Website Rankings http://www.guaranteedrankings.com/ Reply

Thanks for some good points there. I am kind of new to the internet , so I printed this off to put in my file, any better way to go about keeping track of it then printing?

August 21, 2010 6:20 am Google SEO http://www.guaranteedrankings.com/ Reply

Good read … headline catchy … good points, some of which I have learned along the way as well (humility, grace, layoff the controversial stuff). Will share with my colleagues at work as we begin blogging from a corporate perspective. Thanks!

Leave a Comment!

Name
Email
URL
Message