The XMLHttpRequest object

The XMLHttpRequest object is the key component for RPC with JavaScript; these days more commonly known as AJAX.

Although AJAX has been around for years, it is only in recent years that it has really gained popularity. As with most things that suddenly gain massive popularity, it is spreading like a virus, and misconceptions and misuse is spreading equally fast.

However, there is no denying that RPC can be and is a useful tool for various tasks. I wrote this article in an attempt to clarify some things about the usage of this technology. I hope you find it useful.

Creating the object

		xmlReqObj = function() {
			var http = false;

			if(window.XMLHttpRequest) {
				try {
					http = new XMLHttpRequest();
				} catch(e) {
					http = false;
			} else if(window.ActiveXObject) {
				try {
					http = new ActiveXObject("Msxml2.XMLHTTP");
				} catch(e) {
					try {
						http = new ActiveXObject("Microsoft.XMLHTTP");
					} catch(e) {
						http = false;
			return http;

The code above creates the basic object, making sure that it will work in all browsers which support this technology. This is just the function which creates the object, and if you do not understand it, there is no need to worry.

In general, you would put this function in a seperate javascript file and include it in the pages where you want to utilize it, using the following syntax:

		<script type="text/javascript" src="ajax.js"></script>

where ajax.js is the name of the javascript file you put the function in. Althought this is not a requirement, it is a good way of managing your code.

Using it

		var xhr = new xmlReqObj();

This is generally where the average programmer would start his script, as this code creates the XMLHttpRequest object. After that has been done, make sure that you check that the object has actually been created. You have no absolute guarantee that that part will succeed, and the function for creating this object has got fail-safes for this eventuality (i.e. it returns null). So, after this piece of code, you should check to make sure that http is not null.

After you have made sure that the object is functional, you can start the data transfer. Here is an example script:

		xhr.open('POST', 'script.php');

		xhr.send('value1=' + value1 + '&value2=' + value2 '&value3=' + value3);

		xhr.onreadystatechange = callback;

The first part, the abort();, is to ensure that you are not queueing up a ton of requests, in the case that a new request is sent before the previous one has completed. If you want to have multiple multiple requests sent simultaneously, you must use several XMLHttpRequest objects.

The second part is the one which opens the connection to the server. Although many tutorials use GET as the request method, in most cases the script is of such a nature that the HTTP protocol demands the use of POST. In addition, there are caching issues when using GET which you will not get when using POST. Some people have made up some clever scripts to "fix" the caching issues, but there is no need for these.

The third and fourth lines deal with the actual data transfer. It sets the default content-type for form data and then transmits name/value pairs in the same way as a normal HTML form would. The fifth line is covered under the next heading:

Readystate change

After you have sent data to the document, the server will start sending back status reports - ready states. Each of these readyState status reports triggers the onreadystatechange event handler. What you do then is assign a function - named callback in my example - to check what readyState it is currently at, and take the appropriate, if any, actions.

		function callback() {
			if(xhr.readyState == 4 && (xhr.status == 200 || xhr.status == 304)) {
					/* Do whatever you want to do with the returned data */

When readyState gets to 4, the data has been fully loaded, and it is safe to start working with it. There is also a check for HTTP status there to make sure everything is OK. When those checks are passed, you can start doing whatever it is that you wish to do with the data, which is generally retrieved via http.responseText.

Additional notes

You should consider some things when using AJAX. Know that you can risk lower search engine ratings if you use AJAX extensively for displaying content on your site.

You should also consider what you are actually transmitting. Raw HTML data can in many cases cause your application to cease working for no obvious reason, so you should look into various formats for data transfer like CSV or JSON.