[JavaScript] AJAX – XMLHttpRequest

AJAX is a smart way to use JavaScript to update the part of a page asynchronously. In its heart, there is an “XMLHttpRequest” object.

The implementation of “XMLHttpRequest” in major browsers has been undergone a couple of big changes.

 

1. Getting XMLHttpRequest in IE6

In this old browser of MS, ActiveX is used to create an “XMLHttpRequest” object.

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

 

2. Getting XMLHttpRequest Object

Almost all recent browsers support the “XMLHttpRequest” object as a native JavaScript object.

var xmlHttp = new XMLHttpRequest();

In general you can create an “XMLHttpRequest” object like this:

var xmlHttp = null;
function loadXmlHttpObject() {
  if (window.XMLHttpRequest) { // IE7 or later, Mozilla, Safari
    xmlHttp = new XMLHttpRequest();
  } else if (window.ActiveXObject) { // IE6
    try {
      xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
    } catch (e) { }
  }
}

 

3. Sending an Asynchronous Request

To send a request, you need to open the channel first.

  • open(method, url, async, user, password)

And then you can send a request.

  • send(data)

Optionally, you can set the request header.

  • setRequestHeader(header, value)
if (xmlHttp) {
  var url = "data/update.txt";
  xmlHttp.open("GET", url, true); // async = true
  xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  xmlHttp.send(null);
}

 

4. Receiving Response – XMLHttpRequest Version 1

If your main target browser is IE7 or IE8, you need to use the “onreadystatechange” event to handle the response.

xmlHttp.onreadystatechange = onCallback;
xmlHttp.send(null);

In the callback function, you need to check the status code to determine how your request is being processed.

You can look up the reponse-related properties of the “XMLHttpRequest” object.

  • readyState: the state of the request/response
  • status: the response status;
  • statusText: status description
  • responseText: text response body
  • responseXML: document response body
function onCallback() {
  if (xmlHttp.readyState == 4) { // DONE
    if (xmlHttp.status == 200) { // HTTP Success
      var myDiv = document.getElementById("myDiv");
      myDiv.innerHTML = xmlHttp.responseText;
    } else {
      alert("Error: " + xmlHttp.statusText);
    }
  }
}

 

5. Receiving Response – XMLHttpRequest Version 2

In IE9 or other latest browsers supports a little bit cleaner way to handle the response.

Rather than responding any status change through the “onreadystatechange” event, you can only handle the “onload” event.

xmlhttp.onload = onCallback;
function onCallback() {
  if (xmlHttp.status == 200) { // HTTP Success
    var myDiv = document.getElementById("myDiv");
    myDiv.innerHTML = xmlHttp.responseText;
  } else {
    console.log("Error: " + xmlHttp.statusText);
  }
}

 

6. Example

<!DOCTYPE html>
<html>
  <head>
    <title></title>
    <script>
    var xmlHttp = null;

    function loadXmlHttpObject() {
      xmlHttp = new XMLHttpRequest();
    }

    function sendRequest(url) {
      if (xmlHttp) {
        xmlHttp.open("GET", url, true); // async = true
        xmlHttp.onload = onCallback;
        xmlHttp.send(null);
      }
    }

    function onCallback() {
      if (xmlHttp.status == 200) { // HTTP Success
        var myDiv = document.getElementById("myDiv");
        myDiv.innerHTML = xmlHttp.responseText;
      } else {
        console.log("Error[" + xmlHttp.status + "]: " + xmlHttp.statusText);
      }
    }

    function requstAsync() {
      loadXmlHttpObject();
      sendRequest("update.txt");
    }
    </script>
  </head>
  <body>
    <div id="myDiv"></div>
    <input type="button" id="submitBtn" value="Request" onclick="requstAsync()" />
  </body>
</html>

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