New Formatting for XMLHttpRequest

Recently I decided to try reducing the size of hacking the HTTP request for cross browser support in AJAX. This little snippet has been tested and is working.

PHP
1
2
3
4
// new xml http object
var xmlHttp = new XMLHttpRequest() ? new XMLHttpRequest() :
        ( new ActiveXObject("Msxml2.XMLHTTP") ? new ActiveXObject("Msxml2.XMLHTTP") :
        ( new ActiveXObject("Microsoft.XMLHTTP") ? new ActiveXObject("Microsoft.XMLHTTP") : null ) );

I find this new method easier to read and is much more elegant than the method bellow; which is the only method I’ve seen out there.

PHP
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
try{
    // Firefox, Opera 8.0+, Safari
    xml=new XMLHttpRequest();
}catch(e){
    // Internet Explorer
    try{
        xml=new ActiveXObject("Msxml2.XMLHTTP");
    }catch(e){
        try{
            xml=new ActiveXObject("Microsoft.XMLHTTP");
        }catch(e){
            alert("Your browser does not support AJAX!");
            return false;
        }
    }
}

I know that I am not the only who has tried to shorten this section of code. Let me know what you think or how you handle it yourself.

JavaScript
TAGS: , ,
No Comments