How to create XMLHttpRequest Object

Author: satz | Date: May 18, 2010

Creating XMLHttpRequest Objects is one of the most important intial steps in making an ajax request. This article is on how to create an XMLHttpRequest Object. Learn more about the XHR Object.

XHR (XMLHttpRequest) objects are used in ajax applications as a means for browser-server communication. XHR object request are faster than the conventional means of hyperlinks and form submissions.The conenvtional methods are obtrusive because, they would require a page refresh as the response must contain an entire page.

XMLHttpRequest Objects

XMLHttpRequest Object is a JavaScript Object capable of calling the server and capturing its respose. Unlike the traditional methods, this process does not require a page refresh and the response time is very less.

Creating XMLHttpRequest Objects

Most of the modern browsers have the XMLHttpRequest support. However, in Internet Explorer browsers till IE7 XMLHttpRequest was offered only using ActiveX object. The later versions of Internet Explorer would support XMLHttpRequest.

The following function would create an XMLHttpRequest Object in most of the Browsers


 function createXMLHttpRequest() {
 try { return new XMLHttpRequest(); } catch(e) {}
 try { return new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) {}
 alert("Sorry, the XMLHttpRequest is not supported");
 return null;
 }
 var xhrObj = createXMLHttpRequest();