XMLHttpRequest Object in Different Browsers

Listing 1. Accounting for differences in how browsers use the XMLHttpRequest object can be painful. This listing shows a simple cross-browser example of how you can make AJAX requests using the XMLHttpRequest object. The complete code for this example is available in the article's code download.

<script type="text/javascript">
    var xmlHttp = null;
    function Add()
    {
       var x = document.getElementById("txtX").value;
       var y = document.getElementById("txtY").value;
       
       //Create params string to be posted to server
       var params  = encodeURI("x=" + x + "&y=" + y);
       
       xmlHttp = GetXmlHttp("POST","XmlHttpHandler.ashx");
       xmlHttp.onreadystatechange = OnStateChange;
       xmlHttp.send(params);
    }
    
    function OnStateChange()
    {
       if (xmlHttp.readyState == 4)
       {   
           if (xmlHttp.status == 200)
           {
              document.getElementById("lblResult").innerHTML = 
                xmlHttp.responseText;
           }
       }
    }
    
    function GetXmlHttp(verb,url)
    {
       var request = null;
       //Create XmlHttpxmlHttp object
       var ua = navigator.userAgent.toLowerCase();
       if (window.XMLHttpRequest) //IE7, Safari, Mozilla
       {
           request = new XMLHttpRequest();
       }
       else //IE5, IE6
       {
           if (ua.indexOf('msie 5') == -1)
             request = new ActiveXObject("Msxml2.XMLHTTP");
           else
             request = new ActiveXObject("Microsoft.XMLHTTP");
       }
       request.open(verb.toUpperCase(),url,true);
       if (verb.toUpperCase() == "POST") 
           request.setRequestHeader("Content-type", 
             "application/x-www-form-urlencoded");
       return request;
    }
</script>