Snippet. JavaScript. Create XMLHttpRequest Object

This little JavaScript snippet creates a XMLHttpRequest. The XMLHttpRequest object is used to make asynchronous calls to the server, which is widely known as AJAX.

Function xml_http_request

The function xml_http_request will create a XMLHttpRequest. If the browser does not support this feature a NULL will be returned.

function xml_http_request() {
  try { return new XMLHttpRequest();                   } catch(e) {}
  try { return new ActiveXObject("Microsoft.XMLHTTP"); } catch(e) {}
  try { return new ActiveXObject("Msxml2.XMLHTTP");    } catch(e) {}
  return null;
}

Example

var conn = xml_http_request();

if (conn === null){
   // Ajax not supported
}

Updated on: 29 Mar 2024