Introduction to AJAX

Or: ajax_v4 manual
By Oded Sharon

Basically AJAX

AJAX means Asynchronous Javascipt And XML. This means that a client-side code script interacts with a server using XML format. It's asynchornous because we can't really tell how much time will it take for the server to respond. The most important issue in AJAX, is that the client-side receives the response and can do whatever it want with it: show it one the screen, process it or even simply ignore it.

I think it's important to note that AJAX is a technique and not a technology; It's just a mean to do something using other technology artifacts. To be more specific, AJAX relies on heavily on a javascript object called XMLHttpRequest. In practice, you can handle AJAX-like behavior without XMLHttpRequest, by sending command to a hidden iFrame which will tell its parents what to do. It's more complicated. but still possible. check out the example.

... // in the main file
<a onclick="use('iframe_example').src='intro_to_ajax.php?ajax=0';">example</a>
...

... // in the ajax response
class_invert(window.parent.document.getElementById("iframe_example"),"hidden");
...

Internet Explorer uses an activeX object called ActiveXObject("Microsoft.XMLHTTP"). It provides almost the same functionality as XMLHttpRequest and although ajax_v3 support both objects, in this tutorial we'll refer to XMLHttpRequest only.

So, basically, all you need to do in order to have AJAX, is to create an object, define a URL for it and send a string of information that will be recevied by the server-side. The following example will send this page variable called varName with the value varName.

ajaxObj = new XMLHttpRequest();
ajaxObj.open("POST","intro_to_ajax.php",true);
ajaxObj.send("varName=value");

But wait, sure we can send stuff to the server, but we need someone to "catch" its response, so we'll tell ajaxObj that onLoad, it should run our parser function. We should also define what will happen onError, but for terms of simplicity, we'll use the same parser_func for both events.
our parser_func will check the state of our request and if it's completed we'll be able to do whatever we want with the responded text we got from the server. In the next example, we'll simply display it in a message box:

ajaxObj = new XMLHttpRequest(); 
ajaxObj.onload = parser_func
ajaxObj.onerror = parser_func;
ajaxObj.open("POST","intro_to_ajax.php",true);
ajaxObj.send("varName=value");

function parser_func () {
    if (ajaxObj.readyState==4 || ajaxObj.readyState=="complete")
        alert (ajaxObj.responseText);
}

So where does the XML fit in?!

You can live very well without XML, but parsing the complex responds might be easier so you can use the DOMParser object to convert the response to an XML tree and work with it (or ActiveXObject("Microsoft.XMLDOM") for IE). After initialing the DOMParser object, you'll need to give it the result as input, so you'll have var xmlDoc=parser.parseFromString(ajaxCallResponse,"text/xml");.
In the next example, We'll parse our response and display a message box for each >item< in our object.

function parser_func () {
if (ajaxObj.readyState==4 || ajaxObj.readyState=="complete") { var parser=new DOMParser(); var xmlDoc=parser.parseFromString(ajaxObj.responseText, "text/xml"); var taggedList = xmlDoc.getElementsByTagName ("item"); for (var itemCnt=0;itemCnt<taggedList.length;itemCnt++) { // loops through items alert (taggedList[itemCnt].xml); } }

A short history on ajax_vX and different approaches to AJAX

The idea in ajax_vX is to have a generic and simple tool to enable AJAX functionality. It acts as a middleware between the client and the server. Ajax_v1 was completely transparent, allowing clients to send actual code to the server. Since this posed a major security breach, Ajax_v2 asked the client to send codes that will be interperted on the server to acutal commands. However, the codes were limiting and so ajax_v25 offered more codes to allow additional functionalities, Such as applying new CSS style. Ajax_v3 took all the codes gathered in v25 and more and organized it better, while giving more weight on interpeting the result to create diffrent results, like opening a new window. The latest, Ajax_v4 encapsulated v3 into an object and relied on javascript commands to have most of the v3 features (i.e. many features were removed).

ajax_v4 is a primitive

For a starter, ajax_v4 helps you write things shorter. instead of creating a new XMLHttpRequest, you can simply ajax.send ("varName=value", "intro_to_ajax.php")
It will also handle the response, assuming it will be in the following format:

<?xml version=\"1.0\" encoding=\"ISO-8859-1\" ?>
<ajax>
    <item target="myTarget">
        ... content here ...
    </item>
    <item target="target2">
        ... content ...
    </item>
    <script>
        alert ('!'); // standard javascript commands
    </script>
</ajax>

each <item> will be injected to a DOM element with an ID matching the target attribute.
_link will be opened in a new window, assuming the item content is a url. the attibutes listed (seperated by a pipe |) will be applied to the DOM element and the most important thing is the javascript that will run once all the items were injected in our web-page.
This is a very powerful feature as it acutally eliminates the need to have your own parser function. simply let the server tell you which function should handle your response, and the ajax_send will initiate it himself.

Parameters

If, however you insist on having your own parser you can simply add the global javascript variable overrideProcess where its value should be your parser function. If this variable is not null, the ajax_send will call its function instead of using the standard ajax_process function. Note that this function receives one parameter, which is the string received from the server.

overrideProcess=my_func;
ajax.send ("varName=value", "intro_to_ajax.php");

function my_func (result) {
    alert (result);
}

The url variable is used for this specific send command. You can omit it and specify a URL for all your ajax calls using the global javascript variable ajax.url. if it's not defined, ajax.send will try to send the information to the current page and hope it will respond the appropriate XML format.

ajax.url("anyOtherPage.php");	// if you wish to send to the same page
				// you can omit this line completely
ajax.send ("varName=value");

One last parameter that can be used is the global javascript variable debug. When set to true, the ajax_send will issue a message box with the string that is about to be send and a pop-up window with the responded text.

ajax.debug(true);
//calling the method without value, will simply return its value
alert ("Debug feature is now on - "+ajax.debug())
ajax.debug(false);

How does it looks on the server side?

having a xml-supporting web-page is very easy, but not the issue for this article.
What's important is that ajax_send send the entire string as a POST variable called PAR, which should be broken into pieces.
A suggestion for handling AJAX calls on the server-side will be given sometimes in the future.

Synchronous-AJAX ?

having Synchronous-AJAX sounds a bit silly, but I'll give two scenarios where it might be needed:

  • You need to bring a lot of data, and the entire process is too slow.
  • You have several calls, to different servers, but their order is crucial.

ajax_v3 support having SAJAX in two methods; First, each ajax_send returns a call-id, so we can actually sync between calls and make sure that a call will be sent only once another has returned. if a syncTo number wasn't given, zero will be the default (which means it should send right away). Note that if you send null to the url, it will use the default url for this request. see it in action.

var callID = ajax.send ("Step=1");
callID = ajax.send ("Step=2", null, callID);

The second method, which is more simple, but requires work from the server side is to make the second call using the <javascript> code in the previous ajax response. Each method have its advantages; if you have a list of values and wish to send each one in a seperate ajax calls but don't want to run them all at once, the first method will be ideal for you, as you won't need to "remember" the list. However, if you wish to check for user's confirmation or any other validation between calls, the second method will fit your needs better.

Last word on debugging

Although ajax_v4 has a limited debugging features, which can show what is being sent and what was received, I recommend using some browser plug-ings which can show you exactly what was injected to the DOM structre. There are many application for this kind of job, but these are the two I personally use:

Unfortunately, I couldn't find one for Opera, but it got a very good error-console that might detect errors that even my DOM epxlorers wouldn't detect.

Summary

AJAX means chaning the current page using javascript commands in order to interact with the server and enriching it with new information. There are many methods to do. ajax_v4 is a very good starting point for people who just want the job done, and don't want to bury themselves in .net, google or yahoo unecessary code

© 2007. All rights reserved.