0

I am trying to create xml http request object, I can't find where I am going wrong, when I try to alert the object it prints false

var xmlHttpObject = createXmlHttpRequestObject();
alert(xmlHttpObject); // return object is false is my problem 

function createXmlHttpRequestObject() {
  var xmlHttpObject;
  //mozilla browser
  if (window.ActiveXobject) {
    try {
      xmlHttpObject = new ActiveXobject("Microsoft.XMLHTTP");
      alert(xmlHttpObject);
    } catch (e) {
      xmlHttpObject = false;
    }
  } else {
    try {
      xmlHttpObject = XMLHttpRequest();
      alert('test'); //it is not coming in to the block itself
    } catch (e) {
      xmlHttpObject = false;
    }
  }

  if (xmlHttpObject) {
    alert("object created");
  } else {
    alert("object not created");
    return xmlHttpObject;
  }
}
mplungjan
  • 169,008
  • 28
  • 173
  • 236
anbu
  • 35
  • 7
  • You forgot a `new`- `xmlHttpObject = new XMLHttpRequest();` - Also reverse the test since it is likelier you have non-IE. The first part of the code is for IE ignoring your wrong comment of // mozilla – mplungjan Aug 07 '17 at 05:48
  • I am voting to close as _This question was caused by a problem that can no longer be reproduced or a simple typographical error. While similar questions may be on-topic here, this one was resolved in a manner unlikely to help future readers._ – mplungjan Aug 07 '17 at 05:49
  • debugging 101: browser developer tools console (F12 usually) - would show you exactly where and what the error is – Jaromanda X Aug 07 '17 at 05:54
  • @JaromandaX - except it does not give any errors – mplungjan Aug 07 '17 at 05:57
  • 1
    d'oh, of course not ... damn you try/catch :p why wouldn't you `console.error(e)` in the catch block ;) – Jaromanda X Aug 07 '17 at 05:58
  • 1
    https://stackoverflow.com/questions/19638981/window-activexobject-difference-in-ie11 – Paweł Łukasik Aug 07 '17 at 06:00

2 Answers2

0

Simply don't. We got much better tools than XmlHttp right now.

https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API https://www.npmjs.com/package/isomorphic-fetch

wookieb
  • 4,099
  • 1
  • 14
  • 17
0

Just for completeness sake - here is a corrected version of the script taking into account

window.ActiveXObject difference in IE11

var xmlHttpObject = createXmlHttpRequestObject();
console.log(xmlHttpObject); // shows undefined if not created

function createXmlHttpRequestObject() {
  if (XMLHttpRequest) return new XMLHttpRequest(); // Works in most browsers

  // IE 
  var xmlHttpObject;

  if ((Object.getOwnPropertyDescriptor &&
      Object.getOwnPropertyDescriptor(window, "ActiveXObject")) ||
    "ActiveXObject" in window) {
    try {
      xmlHttpObject = new ActiveXobject("Microsoft.XMLHTTP");
    } catch (e) {
      console.log(e);
    }
    return xmlHttpObject;
  }
}
mplungjan
  • 169,008
  • 28
  • 173
  • 236