Akxl Labs C# ASP.NET Articles and Tutorials Akxl Labs Web Apps and Tools for Your Website

Creating the XMLHttpRequest Object for AJAX Postbacks

Tags tagged as   Code: AJAX, JavaScript, Web
A hybrid method for creating a cross-browser compatible XMLHTTPRequest object for AJAX transactions.

Posted October 07, 2006    Viewed 2998 times    Add to DiggAdd to del.icio.usAdd to FURLAdd to RedditAdd to YahooAdd to BlinklistAdd to GoogleAdd to ma.gnoliaAdd to ShadowsAdd to Technorati

Summary

Everyone has their own idea about how to create the XMLHttpRequest object for postback to the server. Since this object is the core of AJAX technology, allowing communication between a JavaScript and the server, it's an important topic to get right. The function below is my favorite, composed of a few different ideas I found in other examples on the web.

When Internet Explorer is present, the object is created using a pre-processor directive, and returned. Otherwise, a check is made to see if the more standard, non-Active-X object can be created and returned. This applies to all non-IE browsers with AJAX support. If no object can be created, the script takes advantage of JavaScript's loosely typed syntax, and returns false.

So, you either get a valid XMLHttpRequest object, or false. This allows for really clean code later on when it comes time to determine if we can use AJAX, and then make some call back to the server.

Articles and downloads sponsored by:
Thanks! Amazon commissions help me pay for textbooks.

Source Code

1 function GetHTTPObject() 2 { 3 var xmlhttp; 4 5 /*@cc_on 6 @if (@_jscript_version >= 5) 7 { 8 try 9 { 10 xmlhttp = new ActiveXObject("Msxml2.XMLHTTP"); 11 } 12 catch (e) 13 { 14 try 15 { 16 xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); 17 } 18 catch (E) 19 { 20 xmlhttp = false; 21 } 22 } 23 } 24 @else 25 xmlhttp = false; 26 @end @*/ 27 28 if (!xmlhttp && typeof XMLHttpRequest != 'undefined') 29 { 30 try 31 { 32 xmlhttp = new XMLHttpRequest(); 33 } 34 catch (e) 35 { 36 xmlhttp = false; 37 } 38 } 39 40 return xmlhttp; 41 }

Comments & Feedback


There are no comments on this entry.
Leave this field blank:
Comment on this Entry
This work is licensed under a Creative Commons Attribution 3.0 United States License.
Please link to this article in your source code comments if you use this content.

Labs

Blog

The blog has moved.
Non-technical articles are now on a seperate site.
Contact me for the new address.

Apps

Real-Time Coffee Counter
add it to your website!
Golden Ratio Visualizer
a tool for design

Coffee Counter

Current Count:
Akxl Coffee Meter
Current Coffee:
 Peet's Malawi Songwe River

The Real-Time Coffee Meter is a free Website App from Akxl Labs. Text-only and badge versions available.