Cross Browser XMLHttpRequest

written by: Carol Rudenberg; article published: year 2006, month 10;



In: Categories » Computers and technology » AJAX and JavaScript » Cross Browser XMLHttpRequest

One of the attributes that have made XMLHttpRequest such a popular transport for AJAX requests is that it is easy to use in a way that is compatible across multiple browsers. The big two browsers, IE and Firefox, provide the same basic API. This consistency makes for a similar development experience. Opera and Safari also support the same basic API, but only in their more recent versions.

When you are writing cross-browser, the first problem you need to overcome is that XMLHttpRequest is an ActiveX object in IE, and it's a normal JavaScript object in Mozilla and the other browsers. There are a number of approaches to overcoming this problem, including optional JScript code for IE, but I find that the simplest solution is just to use exceptions. Below is an example that tries every version of the XMLHTTP ActiveX object, if needed. This helps make our implementation as robust as possible. The function also throws an exception if it's not possible to create an XMLHttpRequest object. This gives us a way to give error messages or to fall back to IFrame requests, if needed.

Cross-Browser XMLHttpRequest Creation
1  // function to create an XMLHttpClient in a cross-browser manner
2  function initXMLHttpClient() {
3      var xmlhttp;
4      try {
5          // Mozilla / Safari / IE7
6          xmlhttp = new XMLHttpRequest();
7      } catch (e) {
8           // IE
9           var XMLHTTP_IDS = new Array('MSXML2.XMLHTTP.5.0',
10                                     'MSXML2.XMLHTTP.4.0',
11                                     'MSXML2.XMLHTTP.3.0',
12                                     'MSXML2.XMLHTTP',
13                                     'Microsoft.XMLHTTP' );
14          var success = false;
15          for (var i=0;i < XMLHTTP_IDS.length && !success; i++) {
16              try {
17                   xmlhttp = new ActiveXObject(XMLHTTP_IDS[i]);
18                      success = true;
19                } catch (e) {}
20          }
21          if (!success) {
22              throw new Error('Unable to create XMLHttpRequest.');
23          }
24     }
25     return xmlhttp;
26 }

The overall pattern of this code is simple: Create an XMLHttpRequest instance in the most optimal way possible, as shown in line 6. This creation should always succeed on Mozilla-based browsers, such as Firefox, on Opera, and on the upcoming IE 7.

If XMLHttpRequest doesn't exist, catch the exception that is thrown, as shown in line 7. Getting an exception means you're on IE or an old browser. To test for IE, attempt to create an ActiveX version of XMLHttpRequest, which is accomplished by the following:

  1. Looping over all possible ActiveX identifiers. This action will create an ActiveX instance for each identifier until the creation succeeds, setting the success flag to TRue, as shown in lines 920.
  2. If creation is successful, returning an XMLHttpRequest instance, as shown in line 25. Otherwise, throwing a JavaScript exception, as shown in line 2

This approach allows for minimal overhead if the browser supports a native XMLHttpRequest object while fully supporting IE. It also gives us an error if XMLHttpRequest isn't supported at all. This error could be displayed to the user at this point, or you could insert another communication approach, such as hidden IFrames.

legal disclaimer

1) Our website is not responsible for the information contained by this article as well for any and all copyright infringements by authors and writers. E-articles is a free information resource. If you suspect this article for any copyright infringements, please read the Terms of service and contact us to investigate the problem.
2) The E-articles directory team is not responsible for inaccuracies, falsehoods, or any other types of misinformation this tutorial may contain and will not be liable for any loss or damage suffered by a user through the user's reliance on the information gained here. Please read the Terms of service

Useful tools and features

Translate this article to...    Send this article to you or to a friend

Link to this article from your page   
If you like this article (tutorial), please link to it from your web page using the information above. Linking to this page, this is the only way to help us improve our service, the same time providing your visitors with a way to improve their online experience.

related articles

1. How I Decide Which Open Source AJAX Library to Use
The company I work for, Uversa Inc., is based around General Public License (GPL) software, so when I pick any library, it first needs to be compatible with the GPL. Because the GPL is so widespread, many licenses are compatible with it. (See www.fsf.org/licensing/licenses/index_html#GPLCompatibleLicenses for more information.) However, because licensing is a hard rule, you should always start your search by limiting it to the ones th...

2. Goals of AJAX
First and foremost, AJAX is about improving user experience; user experience improvements fall into two categories: making current tasks easier and making previously impossible tasks possible. Obviously, it is easier to focus on making current tasks easier. In Web development environments, this can be further broken down into two main goals: increasing interactivity and decreasing the time required to perform a task. In nonintranet cases, you may also have a related technical goal of reducing bandwidth use; by transferring less...

3. XMLHttpRequest Overview
Originally, Microsoft designed XMLHttpRequest to allow Internet Explorer (IE) to load XML documents from JavaScript. Even though it has XML in its name, XMLHttpRequest really is a generic HTTP client for JavaScript. With it, JavaScript can make GET and POST HTTP requests. (For POST requests, data can be sent to the server in a format of your choosing.) The main limitations to XMLHttpRequest are due to the browser security sandbox. It can make only HTTP(S) requests (file URLs, for example, won't work), and it can make requests o...

4. Promises and Problems of Combining AJAX with Other New Technologies
As you work with AJAX, you may hear of related technologies that you can use with AJAX. They fit into two main groups: mature technologies that are widely available in many browsers today, and new technologies that are available only on a specific browser. The mature technologies include Java and Flash. (Flash is the most important because its plug-in is widely installed, and its design is optimized for providing interactive elements and animations to Web sites.) Java can also be used to add interactivity to sites, but its popula...

5. JavaScript as a Primary Development Language for AJAX applications
JavaScript is a powerful scripting language, but deserved or undeserved, it has gained a bad reputation. If you take some time to look at JavaScript with a fresh eye, you will notice that most of its problems no longer exist. The core language is now standardized with the European Computer Manufacturer's Association (ECMA) standards group and is supported on all modern browsers. Of course, these browsers also support older proprietary syntaxes, and you should avoid these as much as possible. Keeping to the standardized interfac...

6. What Is Ajax
Ajax stands for Asynchronous Javascript And XML. Although strictly speaking Ajax itself is not a technology, it mixes well-known programming techniques in an uncommon way to enable web developers to build Internet applications with much more appealing user interfaces than those to which we have become accustomed. When using popular desktop applications, we expect the results of our work to be made available immediately, without fuss, and without us having to wait for the whole screen to be redrawn by the program. While us...

7. Integrating AJAX into a Framework
Whether you're planning to add only a few simple AJAX features or use AJAX throughout your site, integrating it into your current Web site design is a must. The more formal the framework, the harder the process isespecially if your framework provides a front controller that is heavily optimized for generating HTML. Frameworks without a front controller have an easier time incorporating AJAX because they can add a new entry point just for AJAX; many AJAX Remote Procedure Call (RPC) implementations provide code to help do this....

8. Technologies of AJAX
If you search the Internet for AJAX, you are likely to notice a large number of items popping up under the AJAX name that don't seem to fit my definition. In most cases, these libraries provide the related functionality needed to finish your AJAX application, but other times, these libraries are just someone trying to jump on the AJAX bandwagon. When looking at these libraries and techniques, I divide them into three groups: Those directly used in AJAX Those closely related to AJAX ...