Wednesday, December 6, 2006

Simple AJAX Tutorial

Today i was faced with the need to use AJAX in a programming project that i am currently working on. Since this was my first "real" use of AJAX, it took me some time to find a good, easy, and most importantly fast reference to get things rolling. So i decided to add my newfound knowledge, in a form that would hopefully benefit others.

PS: it is assumed in this tutorial that you already possess the knowledge for web programming.

In your web page, you need to add the following JavaScript:

/*This function creates the request object, we check if activeX is available, because Internet Explorer deals with the request object differently than other browsers */
function createRequestObject() {
    if(window.XMLHttpRequest) { // If Safari, Mozilla, Netscape, ...
        request = new XMLHttpRequest();
    } else if(window.ActiveXObject) { // If IE
        request = new ActiveXObject("Microsoft.XMLHTTP");
    }
    return request;
}

var request = createRequestObject();

/*This function sends the request, and defines the response handler. Notice that when we define the response handler, we mention the function name, we do not add paranthesis after it, nor do we pass it a parameter list. We simply define it, not call it. The open method opens a connection to the specified URL, to send the request to. */
function sendRequest(url) {
    request.onreadystatechange = responseHandler;
    request.open("GET", url);
    request.send(null);
}

/*This function is called when the request state changes. If request is complete and OK, then we process the result. */
function responseHandler(request) {
    if(request.readyState == 4) { //If request complete
        if(request.status == 200) { //If request OK
            var string = request.responseText;
            //Process response
        }
    }
}

All the previous code would be run and executed on the client machine. You just need to connect the sendRequest function with an event in your page, such as onClick button, or onChange select.
On the server side, you simply need to create a page which request.open connects to, read the parameters in your GET request, do some processing, and echo the results.

Of course, AJAX has so much more to it than this rather simple example. But this is meant as a starting point, to get things rolling fast. AJAX contains so much more, from using POST to send the request, to accepting XML as a response. The only limit is your imagination!!

--
Links i used to gain this knowledge:
1- Rasmus' 30 second AJAX tutorial
2- Mozilla Developer Center

5 comments:

Hourani said...

hey man!
nice post, but the only limit is not your imaginations ;) ..
please notice that XMLHttpRequest has a basic security restriction prevents you from making XMLHttpRequests to any server except the server where your web page came from. To access third party web services, XMLHttpRequest needs to be fixed and those fixes are outlined as:
-Creating Application Proxies
-Using Apache Proxy
-Script tag hack with application proxy.

thank you for the extraordinary post mano :)

Al-Faisal El-Dajani said...

Thanx for the clarification. That point of advice is available on the second link of the resources i used to write that article. But i thought such things should be left out at the moment. This is not a full AJAX tutorial, just a point to start at.

al ghoul said...

I heard the term AJAX before. I used some hints I found on http://hoctro.blogspot.com/ to tweak my blog page. I don't really understand what AJAX really does. I'm glad you're going to be posting stuff about coding. I have a very basic idea in programming. I'm glad you're doing some coding help here for novice users like me.


peace

Al-Faisal El-Dajani said...

AJAX stands for Asynchronous Javascript And XML. It is a new technique in programming that utilizes already available technologies to enhance the web applications interactivity.

Ok, now in english words.
AJAX is a way to make web applications more user friendly, because web applications always suffered from being far slower than desktop applications and less interactive.
For instance, imagine a web interface where you need to register for an email account. You choose your username, fill some data in, and click submit, only to be redirected to the same page telling you that the username is already in use.
If you were using AJAX, when the user enters the desired username, they can continue to fill the form, while username availability check would be run in the background asyncrhonously. This greatly enhances the user experience, since they don't need to keep reloading the page to find out the latest information available.
Another use is for interactive menus. Imagine a site that shows you two menus, where one contains the name of countries, and the second shows you the names of cities within the country you choose in the first menu. This was done either reloading the entire page once you chose a country, or by loading all possible countries and cities when the page first loads and then using javascript to display the appropriate informaiton.
With AJAX you no longer need to use either of those extremely slow techniques. When the user selects a country, an asynchronous request is sent behind the scenes to fill the second menu with appropriate values.

Hope i made it a bit clearer.

al ghoul said...

thanks ... that does make it clearer