AJAX Asynchronous Get

The most simple AJAX method is the asynchronous get method. While you may wish to create your own AJAX function, it is far easier to get a free one at http://www.nczonline.net/downloads/. At that site, you want to download the zXML functions. If you wish to use your own or another AJAX function, just substitute zXML below with your own function.

This really simple example will replace some text dynamically. This example, and all the ones that will follow, will show the source code in its entirety, and then examine it in more detail later. We will be executing the request asynchronously. This means that nothing on the page will wait for the AJAX page to respond. If the AJAX response is delayed, everything else can continue on as normal. Unless you have a special need, you should send the request asynchronously by default.

First, create a web page that takes a GET variable named MyNumber and doubles the number. If the variable is not a number, output an error message. For this example, it is very important that there is no extraneous information in the output. Manually test the page first. You should do that for every page to avoid problems down the road. Be sure to view the rendered source of the page to make sure there isn't any extra information.

Next, create the main page. Use the example below as a guide.


<script type="text/javascript" src="/zxml.js"></script>
<script type="text/javascript">
function sendAJAX() {
	var oXHR = zXmlHttp.createRequest();
	oXHR.open("get", "action.cfm?MyNumber=" + document.getElementById("input1").value, true);
	oXHR.onreadystatechange = function() {
		if (oXHR.readyState == 1) {
			// checking ...
		}
		if (oXHR.readyState == 4) {
			if (oXHR.status == 200 || oXHR.status == 304) {
				document.getElementById("output1").innerHTML = oXHR.responseText;
			}
			if (oXHR.status == 404 || oXHR.status == 500) {
				alert("An error has occured.");
			}
		}
	};
	oXHR.send(null);
}
</script>
<input type="text" name="input1" id="input1" onkeyup="sendAJAX();" />
<p>I will double your number: <span id="output1">Output goes here.</span></p>

Okay, now to break it down. The first line is the file with the AJAX code, either the one you downloaded or the one you created. That is required. The next few lines get our code started.

var oXHR = zXmlHttp.createRequest();

This line defines the AJAX object. If you wish to discard the old object, simple create a new request later on in the code.

oXHR.open("get", "/action.cfm?MyNumber=" + document.getElementById("input1").value, true);

The parameters of the open method are ("get" or "post", the complete file name, "true" or "false"). If the last parameter is "true", the AJAX request will be sent asynchronous; "false" sends the request synchronous, and the web page will be delayed until the request is received. The document.getElementById("input1").value is the current value of our input field at the bottom of the page. You can put that information in a variable if you want. You may wish to do that if you use that information more than once. The + symbol is the JavaScript method of string concatenation. Since this website supports ColdFusion but not PHP, our AJAX page has the .cfm ending. That doesn't matter, the only thing that matters is the output from that page.

oXHR.onreadystatechange = function() { ... };

We are creating a new function within this object. This is just how the AJAX variable works. This function is executed at various times after the AJAX request is sent. Please note that we have yet to actually send the AJAX request, even though we already specified to open a file. We are just doing the preparation right now. Don't forget about the semicolon at the end of the function.

if (oXHR.readyState == 4) { ... }

The code between this if statement is executed at the time that readyState is recieved. If the code is outside that block, it will not be executed at the time you want, but at an earlier time. After the request has been sent, the created function is called 4 times. While it is being called, the object sets a variable in the object called readyState to let you know at what stage the request is at. The only two states you need to know about are 1 and 4. A readyState of 1 means the request has just started. You may wish to put information in there to let the user know the request is being executed. Of course, you can just as easy not check for a readyState of 1. A readyState of 4 means that a response has been received. This is the most important part of this function.

if (oXHR.status == 200 || oXHR.status == 304) { ... }

When the readyState is 4, another variable in the object is set called status. This is the HTTP status code. A 404 status is page not found, 500 is internal service error, 200 and 304 are when everything is fine. It is in these blocks that you want to put the code you want to process when everything is done. In our example, we just put one line, but you could put a function to execute in there if you want, or many other lines, or whatever.

document.getElementById("output1").innerHTML = oXHR.responseText;

All of the output from the AJAX page is put into the object variable responseText. Since our AJAX page only returns just the text we want to output, we do not need to anything else fancy. So we are going to dynamically put it in the HTML tag with the ID of output1.

oXHR.send(null);

Finally, the request is sent. This should be the last part of your AJAX request. It is an easy part to forget.

And there you have a simple AJAX example. Try it out, and then make your own that something slightly different.

In our example, the output is delayed by 3 seconds to illustrate how the code works asynchronously. You do not want to put the delay in your own code.


See it in action

Manual test of the AJAX page: http://www.techs-on-call.biz/ajax/asynchronous-get/action/action.cfm?MyNumber=2 - http://www.techs-on-call.biz/ajax/asynchronous-get/action/action.cfm?MyNumber=Not-A-Number

The whole page in action: http://www.techs-on-call.biz/ajax/asynchronous-get/action/

[AJAX index]