Code: Ajax Wrapper Function for XHR

Chapter 8 - Ajax Optimization

The most basic Ajax request that you would make will likely employ a simple wrapper function such as this, ordered in preference for native and more modern implementations first:

function createXHR( )
{
    try { return new XMLHttpRequest( ); } catch(e) {}
    try { return new ActiveXObject("Msxml2.XMLHTTP.6.0"); } catch (e) {}
    try { return new ActiveXObject("Msxml2.XMLHTTP.3.0"); } catch (e) {}
    try { return new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) {}
    try { return new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) {}
    return null; // no XHR support
}

Now you can just create an XHR with a simple call:

var xhr = createXHR( );

Once you've created the XHR, use the XHR object's open( ) method to begin forming the request that you are interested in, specifying the HTTP method, URI, and a Boolean value that indicates whether the request is to be synchronous or asynchronous. In this case, true means that you want it to be asynchronous or have a nonblocking behavior, which is the default for the object:

xhr.open("GET","helloworld.php",true);