Search code examples
javascriptajaxxmlhttprequestajaxform

Meaning of window.XMLHttpRequest? (Ajax)


I have a question about this code:

var Request = false;

if (window.XMLHttpRequest) {
   Request = new XMLHttpRequest();
} else if (window.ActiveXObject) {
   Request = new ActiveXObject("Microsoft.XMLHTTP");
}

What is the use of if(window.XMLHttpRequest) and if(window.ActiveXObject)?


Solution

  • The if (window.XMLHttpRequest) part checks if an XMLHttpRequest object can be created without throwing an error.
    If everything goes well, it assigns a name to the object that will be used for "talking with the server".
    If this throws an error, it means that the user has an older browser (IE 5 or IE6), so instead it tries to create an ActiveXObject which is essentially the same but works only for these older browsers.

    You can find more information about this in MDN.