Categories
IE Solutions Tips

XMLHttpRequest error in IE8 and 9

Don’t you hate when everything is going smoothly with your website, you haven’t done anything to it, it is the same since forever and suddenly…. Your ajax is not working in Internet Explorer. Suddenly customers start calling that they cannot log in, or documents are not displaying; A complete mess!!.

Well it happens to me yesterday; since then I’ve been googling and binging for a solution and this is it. This is the solution that best suite my problems:

function getXML()
{
    var req;
    try {
        req = new XMLHttpRequest();
    } catch (trymicrosoft) {
        try {
          req = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (othermicrosoft) {
          try {
            req = new ActiveXObject("Microsoft.XMLHTTP");
          } catch (failed) {
            req = null;
          }
        }
    }

    if (!req){

      return null;
    } else {
       return req;
    }
}

if(getXML()){
    var xhttp = getXML();
} else {
    alert("Error initializing XMLHttpRequest!");
}

First of all I create a function to request the XMLHttpRequest Object, but as you know IE 5 and 6 doesn’t recognized this type of object so you need to catch the error and request an ActiveXObject(“Msxml2.XMLHTTP”) that might work with Internet Explorer 6 and 5 but for earlier versions you need to request an ActiveXObject(“Microsoft.XMLHTTP”) object.

The problem I found is that I only request for the first two, following the sample code provided by w3schools.com, and it was perfect until yesterday. I need it to type back the old function as usual. Don’t know why? Probably MS is no longer accepting XMLHttpRequest or I don’t know I’m not a guru.

The only thing I know this fixed my problem.

Finally, I filter the code so if the xhttp variable is still null pop up a warning saying that the object was not loaded!

Hope this help anyone, Happy Coding!

One reply on “XMLHttpRequest error in IE8 and 9”

Another thing I start doing is creating a new object instead of using a global variable for the request. For example:

If you have a ajax function review the object and then if it’s true create the object

function ajaxfunctio…
if (getXML() ) then
var xm = getXML();
xm.open(‘POST’,url,true); … etc.
end function

Leave a Reply