Ajax - the XMLHTTPRequest

Didn't find what you want? Try our search

Ajax (Asynchronous Javascript And XML) is a technique (or, more correctly, a combination of techniques) for submitting server requests 'in the background' and returning information from the server to the user without the necessity of waiting for a page load.

Ajax is actually a combination of several technologies working together to provide this capability.

How does it work?
Instead of a user request being made of the server via, for example, a normal HTTP POST or GET request, such as would be made by submitting a form or clicking a hyperlink, an Ajax script makes a request of a server by using the Javascript XMLHTTPRequest object.

Although this object may be unfamiliar to many, in fact it behaves like a fairly ordinary javascript object.  As you may well know, when using a javascript image object we may dynamically change the URL of the image source without using a page refresh. XMLHTTPRequest retrieves information from the server in a similarly invisible manner.

How is it coded?
There are a few, relatively simple, steps to coding an Ajax application.  The description below is an attempt to describe the salient points without bogging down the new user in too many of the technicalities.

Firstly, we need to know how to create an XMLHTTPRequest object.  The process differs slightly depending on whether you are using Internet Explorer (5+) with ActiveX enabled, or a standards-compliant browser such as Mozilla Firefox.

With IE, the request looks like:

http = new ActiveXObject("Microsoft.XMLHTTP");

whereas in a standards-compliant browser we can instantiate the object directly:

http = new XMLHttpRequest();

NOTE ON BROWSERS:
When you're experimenting with Ajax applications, it's important to check that your programs work in all of the commonly-used browsers. It always surprises me that so many Windows users don't install other browsers - at the very least, Firefox - to try in addition to Internet explorer. It's free, has pop-up blocking, tabbed browsing, as well as privacy and security features, and a rapidly-exoanding user base. If you run Windows, you can install Firefox alongside IE and compare the results in both. Why not take a moment to get it now?

There is a more detailed discussion of the XMLHTTPRequest object here and examples of code to create the object here, which clearly demonstrates the different approaches for the different browser types.

Next: Getting Data from the Server > > >

Think this may help others? Please share ...Google+FacebookPinterestStumbleUponLinkedInTwitter

Before using any software from this site, please see the Terms




2 Users Online.

All of the code and information on this site is provided free of charge (but without warranty).
If you feel that the site has been useful, you may care to donate a little toward the running of the site and the development of further projects?