Wednesday, August 27, 2008

How to Create XmlHttpRequest Object

It's a bit difficult .
Because each and every browser vendor implemented this XmlHttpReuest object in their own style.
if we take a look at this XmlHttpRequest object implmentation there are two types one is Microsofts Approach is in the form ActiveXObject.
Good what about browsers that doesn't support ActivexObjects .
Browsers like Firefox,Mozilla,Opera,Safari... etc implemented this XmlHttpRequest object as Built in Javascript object.
Note: in Internet Explorer 5.5 version XmlHttpRequest is implement in "MICROSOFT.XMLHTTP" and in version 6.0 it is "MSXML2.XMLHTTP".
we can create XmlHttpRequest object using a try catch block or If Else structure now we will see both of them.
First:
Using Try Catch
function createXmlHttpRequestfun()
{
var XmlHttp=null;
try{
XmlHttp=new XmlHttpRequest(); // for opera,firefox,safari... etc
}
catch() //if it fails it must be interent explorer
{
try
{
XmlHttp=new ActiveXObject("Microsoft.XMLHTTP"); // check whether it is a IE 5.5
}
catch
{
XmlHttp=new ActiveXObject("Msxml2.XMLHTTP"); // check whether it is a IE 6.0
}
}
if(XmlHttp==null)
{
alert("Browser Doesn't support Ajax");
return null;
}
else
return XmlHttp;
}

2)
Now Using If Else
function createXmlHttpRequestfun()
{
var XmlHttp=null;
if(window.XMLHttpRequest) //Checking whether it is a firefox,opera...
{
XmlHttp= new XMLHttpRequest();
}
else if(window.ActiveXObject)//Checking whether it is a IE or not
{
XmlHttp= new ActiveXObject("Microsoft.XMLHTTP"); //for IE 5.5
if(XmlHttp==null)
XmlHttp= new ActiveXObject("Msxml2.XMLHTTP"); //for IE 6.0
}
if(XmlHttp==null)
{
alert("Browser Doesn't support Ajax");
return null;
}
else
return XmlHttp;
}

No comments: