Docstoc

Ajax

Document Sample
Ajax Powered By Docstoc
					AJAX Tutorial

Introduction

This tutorial assumes that you have the basic knowledge of HTML, JavaScript and the basis of the client-server
model. That is all you need to start building basic AJAX applications.

What is AJAX?

Just for your information, AJAX stands for Asynchronous JavaScript And XML. But don’t pay much attention to the
name; it is unfortunately chosen. What you need to know is that AJAX is not a new technology, it is a combination
of existing technologies like HTML, JavaScript, DHTML and DOM. Really it’s just an innovative approach to
combine these technologies to suit the needs of the always developing web applications.

What can AJAX do for you?

AJAX can make your webapps more user friendly. Perhaps the easiest illustration is when a user is filling some king
of form as a part of your webapp and based on the partial user input you can perform a database check
transparently to the user while he is still busy with filling the rest of the form. As a result of that asynchronous
request you can assist the user with various information(like username is taken, auto fill the rest of the form…)
making the GUI of the webapp user-friendly like the one of a standard stand-alone application.

Mixing the Technologies

Here are the basic technologies involved in AJAX:

      HTML is used to build web forms and identify fields that you’ll use in the rest of the webapp
      JavaScript code is the code used in AJAX to facilitate communication with server applications
      DHTML, of Dynamic HTML, helps you update your forms dynamically through usage of div, span and other
       dynamic HTML elements
      DOM, the Document Object Model, is used to work with both the structure of your HTML and (in some cases)
       the XML returned from the server.

The XMLHttpRequest object

In this second part of this tutorial we'll take a look at the XMLHttpRequest object; object that you'll need in order to
make asynchronous requests to the server logic. It's quite simple and most of the time you'll either retype the creation
and request code of use ctrl-C/V. So, let's get started.

What is XMLHttpRequest object?

Basically, it is a JavaScript object, nothing more. Here's the code you need to create it:

Listing 1. Create a new XMLHttpRequest object
 <script language="javascript" type="text/javascript">
         var xmlHttp = new XMLHttpRequest();
 </script>


What it should be clear to you about this object is that this is the object that does the communication with the server
logic using JavaScript technology, nothing more. So, what AJAX basically does is that it puts this object between
your webapplication user forms and the webserver logic(some script, like cgi, php, jsp/servlet..). This is the new
thinking that lets the web application to have the user interface friendliness like a desktop application, but with all the
power of the Internet behind it.

Dealing with Multiple Browsers
Unfortunatelly, the proper creation of the XMLHttpRequest object is not so simple thanks to the variety of browsers.
For example, the above code will work with Microsoft browsers. Without getting further in the problems, I'll simply
present a code that you can use that will create the XMLHttpRequest object no matter the browser and report an error
message if the client has JavaScript disabled in her/his browser. Here's that code:

Listing 2. Dealing with various browsers
 var xmlHttp = false;
 /*@cc_on @*/
 /*@if (@_jscript_version >= 5)
 try {
          /* try the first version of JavaScript in IE */
          xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
 } catch (e) {
   try {
          /* try the second version of JavaScript in IE */
     xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
   } catch (e2) {
     xmlHttp = false;
   }
 }
 @end @*/
 /* else create the object the non-Microsoft way */
 if (!xmlHttp && typeof XMLHttpRequest != 'undefined') {
   xmlHttp = new XMLHttpRequest();
 }



Don't mind the fancy compiler-spicific tags like @cc_on, just remember that this is the code that you can rely on to
sucesfully create the XMLHttpRequest no matter the browser.

Adding some standard JavaScript

We know how to create the XMLHttpRequest object that we need in order to communicate with the server logic
(invoke a particular script). Now we need to learn how to put information in this object in order to pass information
to the web server that the script needs in order to satisfy the request. Next, we need to make the request and receive
the response that we can use to update the form that the user is woking on. Suppose the following scenario:

The user of our web application is using a form to modify the information regarding a warehouse item already stored
in the database. In most cases, the user will want to change a field or two about the item(eg. new address and website)
but wants to view all the current information about the item. Instead of requiring the user to rewrite ALL the
information about the item, we can use AJAX to detect the selection of the itemID from an drop-down menu and use
that info to fetch the appropriate related data for the item from the database. This means that the user in a second or
two will have all the information for the item auto-filled in the form and can only modify the ones it needs. That's the
user-friendliness I was talking about earlier. The code to do such a thing is not complicated. In the following sections
I'll present and explain the parts needed for that code and in the final section we'll reassemble that whole code. So let's
get started!

1. Preparing our user form

First, we need to slightly modify our user form in order for it's elements to be accessible through our code. Again, this
is not something new it's just regular HTML. This typically means adding id attributes to our form elements in order
to identify those elements and using the onChange attribute to specify the action that should be taken when its value
changes( the user types something on it or selects it from drop-down menu ). To simplify our code we consider that
the user types the itemID in a input field. The exactly same attributes(id and onChange) can be added to drop-down
menus or whatever form element. Here's the code:

Listing 3. Preraring out input form for some AJAX usage
 <form...>
 <input type="text" name="itemID" id="item"
                         onChange="callServer();">
 (...may add other elements here using usual HTML...)
 </form...>
 <div id="newForm">
         On this place a whole pre-filled form
         will appear according to the selection of
         the itemID field. This form will the created
         by the server.
 </div>



There are two things to remember(in case you never used them in your HTML's): the id attribute whose value we'll
use in our AJAX(well the JavaScript part of AJAX) code to retrieve the values from the form elements and to
dispatch those values to the server logic, using XMLHttpRequest ofcourse.
The second onChange attribute is used to indicate which JavaScript method to invoke in order to process the event
that has occured, that is, the user typed something in the field. That method, in this case, is named callServer, but can
be any other name.

2. Creating the XMLHttpRequest, dispatching the request and handling the response

In this step, we create the XMLHttpRequest object, that is the object that is responsible for handling the
communication between the client and the server, we retrieve the user-entered itemID from the form, issue a request
to the server with the retrieved parameter as argument to that request and handling the server response. The creation
of the XMLHttpRequest object is exactly the same as above, and the same code is used here. Now look at the code
and afterwards we'll see and explain the new things:

Listing 4. Creating XMLHttpRequest and issuing the request
 /* Creating the XMLHttpRequest same as above */
 var xmlHttp = false;
 /*@cc_on @*/
 /*@if (@_jscript_version >= 5)
 try {
          /* try the first version of JavaScript in IE */
          xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
 } catch (e) {
   try {
          /* try the second version of JavaScript in IE */
     xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
   } catch (e2) {
     xmlHttp = false;
   }
 }
 @end @*/
 /* else create the object the non-Microsoft way */
 if (!xmlHttp && typeof XMLHttpRequest != 'undefined') {
   xmlHttp = new XMLHttpRequest();
 }

 /* the 'new' part:*/

 /* 1. retrieving the entered data and
 issuing the request */
 function callServer() {
         //Get the itemID value from the form elements
         var item = document.getElementById("item");

           //check whether the element has value
           if((item==null) || (item=="")) return;
           //make the URL that will process the request
           var url = "/scripts/getItemInformation?item="
                           +escape(item);

           //make a connection to the server
           xmlHttp = OPEN("GET",url,true);

           // Setup a function for the server to run when it's done
           xmlHttp.onreadystatechange = updatePage;

           // Send the request
           xmlHttp.send(null);
 }

 /* 2. handling the server response */
 function updatePage() {
         if (xmlHttp.readyState == 4) {
     var response = xmlHttp.responseText;
     document.getElementById("newForm").value = response;
   }
 }




Now, let's clear things up. In the first part we create the XMLHttpRequest object as usual. Afterwards, we dispatch
the request to the server. The substeps used are to retrieve the value using getElementById(that's why we specified
the id attribute previously when we were preparing our form for AJAX/JavaScript usage. Afterwards, we checked
whether the value retrieved is valid and build the URL to the server script that will process the request passing the
retrieved data as it's parameter. Then, we opened the connection to the server declaring that we're going to use a GET
request(in a future tutorials i'll cover the POST request), the URL we've just build and a boolean literal of true(don't
worry about the meaning, just know it's should be true). Next, we declare which function should be invoked when the
server finishes the processing of our request which is updatePage in our case. In the last step, we effect the things
that we declared in the previous steps by issuing a send(null) call to the XMLHttpRequest object we created
previously.
What's left is to implement the updatePage function that will handle the response and make the changes to the user
form. In the first line we check whether it is safe to use the response(checking whether the server has finished with
the generation of the response for sure). Don't worry about its meaning, just know that when readyState has a value
of 4 you're safe with using the response, no matter the browser. In the last line, we just display the result from the
server to our form. In our case, the response is a newly generated form that has it's fields preset to the appropriate
values specific to the selected itemID field by the user. We're just taking that whole prepared response and we're
putting it in display in our form.
As a result of this, our user just after selecting the itemID will get a brand new preset form on it's page, asking it to
just modify the fields he feels need changes. That's the user-friendliness of the webapp GUI that was not possible
with the standard way of thinking about the client/server requests.

An end note

The abobe illustrative example is just one example of the AJAX approach. Use your creativity and think of the
possible applications that AJAX can have in order for you to make rich, responsive web applications. We have to
admit that no matter how efficient, clever and innovative your underlying application logic is, without the ease of use
and the impressive GUI, in the eyes of the user your application will be dull and repulsive!

This isn't goodbye!

I hope I helped you to learn the basis of the AJAX approach and I sincerely hope that in the past hours you've actually
lerned something from this tutorial. If so, please drop me a note at ipenov@gmail.com and tell me how can I
improve it. In the meantime, visit this page for some more tutorials and software.
Thanks, Ice

				
DOCUMENT INFO
Shared By:
Stats:
views:55
posted:3/3/2010
language:English
pages:5
Description: Ajax_pdf.pdf - Search ajax tutorial introduction this tutorial assumes that have ... Ajax-tutorial.pdf - Search simple ajax tutorial stephan spies ...