Sample Ajax Request

by Ryan Morris

HTML

<span id="ajaxButton" style="cursor: pointer; text-decoration: underline">
  Make a request
</span>

<div id="container">Pending...</div>

CSS

#container{
    border:1px solid #000;
    padding:5px;
    background-color:#ccc;
    overflow:auto;
    height:300px;
    width:90%;
}

JavaScript

(function () {
    
    var httpRequest;
    
    document.getElementById("ajaxButton").onclick = function () {
        makeRequest('/');
    };

    function makeRequest(url) {
        
        console.log("Beginning makeRequest");
        
        // 1) first create the Request object
        if (window.XMLHttpRequest) { // Mozilla, Safari, ...
            
            httpRequest = new XMLHttpRequest();
            
        } else if (window.ActiveXObject) { // IE
            
            try {
                
                httpRequest = new ActiveXObject("Msxml2.XMLHTTP");
                
            } catch (e) {
                
                try {
                    httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
                } catch (e) {}
            }
        }

        if (!httpRequest) {
            alert('Giving up :( Cannot create an XMLHTTP instance');
            return false;
        }
        
        // 2) Tell it how to handle the response
        httpRequest.onreadystatechange = alertContents;
        
        // 3) initiate the request
        httpRequest.open('GET', url);
        
        // 4) Set any headers
        
        // 5) Submit the request
        httpRequest.send(null);
    }

    // New XHR spec includes progress event and listeners
    // 5. Handle the request response
    function alertContents(httpRequestProgressEvent) {

        console.group("Request Handler Fired");
        
        console.log(this);
        console.log(httpRequestProgressEvent);
        
        console.log(this.readyState);
        
        try{
            console.log(this.status);
        } catch(e) {
            console.log("No status");
        }
        
        // if "done"
        if (this.readyState === 4) {
            
            console.log("Done");
            
            // if "ok"
            if (this.status === 200) {
                
                console.log("OK");
                
                // do something...