Home /JavaScript/XMLHttpRequest Object

XMLHttpRequest Object

For now, let's discuss what an AJAX XMLHttpRequest Object is. It is an object that we use in AJAX that allows us to talk to a server behind the users back. This object is the sole reason we are allowed to make updates into the user's page without forcing them to reload the entire page.

An HTTP Request is actually sent out by your browser each time you type a website, which is then sent to a server that finally sends you back the web page. Of course, this happens right before your eyes and you know what it is doing. The XMLHttpRequest is very much like that, but it is very sneaky. The XML is simply a reference to the data structure that is being returned.

Creating an XMLHttpRequest

var xmlhttp;
if (window.XMLHttpRequest) { // works with IE7+, Chrome, Firefox, Safari
    xmlhttp = new XMLHttpRequest();
} else { // works with IE6, IE5
    xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}

To GET Or To POST?

GET is usually the best because it is faster. However, you might want to use POST when you are transferring a very large amount of data. GET actually has a limit to the maximum allowed size for a url.

GET Example

PHP File

<?php
    echo $_GET['sampleVar'];
?>

HTML File

<script type="text/javascript">
function doGET() {
    var xmlhttp;
    if (window.XMLHttpRequest) {
        xmlhttp = new XMLHttpRequest();
    } else {
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }

    xmlhttp.onreadystatechange = function() { //This part is actually executed last
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { // Was the request processed successfully?
            document.getElementById("sampleDiv").innerHTML = xmlhttp.responseText;
        }
    }
    xmlhttp.open("GET", "ajaxTest2.php?sampleVar=" + Math.random());
    xmlhttp.send();
}
</script>

<button type="button1" onclick="doGET()">GET</button>
<div id="sampleDiv">Nothing is here</div>

Understanding the Code

1. When you click button1, it calls the doGet() function which sets up the XMLHttpRequest.

2. We prepare the request with xmlhttp.open():

  • "GET" specifies the request type
  • ajaxTest2.php is the target URL
  • sampleVar is set to Math.random() to prevent browser caching

3. xmlhttp.send() sends the request to the server.

4. When data returns, the onreadystatechange function fires and updates the sampleDiv's content with the random number from the server.