Basics of Ajax
 
Published: 18 Sep 2007
Abstract
In this article Debjani describes everything that one needs to learn about AJAX starting with what AJAX is, how to make an HTTP request and handle a response, the advantages and disadvantages of using AJAX, and when to use and when not to use AJAX.
by Debjani Mallick
Feedback
Average Rating: This article has not yet been rated.
Views (Total / Last 10 Days): 36631/ 39

Introduction

Ajax is the shorthand notation for Asynchronous JavaScript and XML. It is a web development technique that is used for developing interactive web applications. Ajax develops interactive web application by sending a small amount of data to the server behind the scenes. The advantage of this is that the entire page is not reloaded every time when the user makes some changes in the input. It may seem that Ajax is some new technology. But that is not true. It is a new way of combining old technologies and representing them in a new way.

·         XHTML and CSS - for presentation

·         Document Object Model (DOM) - for dynamic display and interaction

·         XML and XSLT - for data interchange and manipulation

·         XMLHttpRequest - for asynchronous data retrieval

·         Java Script - for binding everything together

Before going deep into Ajax, let us discuss some basics of web applications. When a person sits down to develop an application, he has two choices before him.

·         Desktop application

·         Web application

Desktop applications normally come on a CD or are sometimes downloaded from some web site and are installed completely on the computer. Desktop application may use Internet sometimes to download some updates, but the code which is responsible for running those applications reside on the desktop only. On the other hand, Web applications run on a Web server which is present somewhere else and a person accesses those applications with the help of his browser.

Desktop applications are pretty fast since they do not require any Internet connection to run and they have great user interfaces. They are also incredibly dynamic. A person can pull up menus and sub-menus and can do many more things without waiting for anything. And this feature is almost opposite to what happens in a web application. No doubt that the services provided by Web applications can never be provided by any desktop application, but it is also true that the user has to wait for everything in a Web application. Since Web applications use an Internet connection they are normally slower that desktop applications. A user has to wait to get a response back from the server, for the web page to get refreshed, etc.

Now coming down to our topic, normally what happens in most of the classical web application is that any user request sends a HTTP request to a web server. The server does some processing to give back the response and then returns an HTML page to the user. But every time the user submits the page to the server, the server responds with a totally new page which makes the application run slower and is less user-friendly. An Ajax application eliminates this disadvantage by incorporating a middle layer between the user and the server. That intermediate layer is the Ajax engine.

Actually, what happens here is that instead of loading a web page, at the start of the session the browser loads the Ajax engine. The Ajax engine is written in JavaScript and is usually placed in a hidden frame. This engine is responsible for communicating with the server and the user; i.e. it acts as the link between the server and user machine. The Ajax engine allows asynchronous interaction of the user with the application, independent of communication with the server. So here, the user does not have to keep waiting for the response from the server. In Ajax every user action that would create any HTTP request takes the form of a JavaScript call to the Ajax engine. Any user request that can be fulfilled by the engine is done by the engine itself without bothering the server. But any user request which requires the server interference, the engine makes those requests asynchronously, usually using XML, without stopping the user interaction with the application.

How to make an HTTP request and handle the response?

In order to make an HTTP request to the server using JavaScript, an instance of a class that provides this functionality is required. Such a class was originally introduced in Internet Explorer as an ActiveX object and is called XMLHTTP. Then Mozilla, Safari and other browsers also followed and started implementing an XMLHttpRequest class that supports the methods and properties supported by Microsoft's original ActiveX object.

Create a new XMLHttpRequest

Listing 1

<script language="javascript" type="text/javascript">
  var XMLHttp=new xmlHttpRequest();
</script>

This is the object which handles all the server communication.

In normal Web applications the users fill out form fields and then click a Submit button. Then, the entire form is sent to the server which passes it on to some script. When the script has finished its work, it sends back a completely new page as the response. But during the time the script or program on the server is processing and returning a new form, users have to wait the entire time.

But in the case of Ajax, it puts the Javascript technology and the XMLHttpRequest object between the user's Web form and the server. When users fill out forms, the data, rather than being directly sent to the server, is sent to a Javascript code. Thus, here Javascript code catches the form data and sends a request to the server.

In order to create a cross-browser instance (object) of the required class we need to write the code.

Listing 2

if (window.xmlHttpRequest)
{
  // for Mozilla, Safari, etc.
  XMLHttp = new xmlHttpRequest();
}
elseif(window.ActiveXObject)
{
  // for Internet Explorer
  XMLHttp = new ActiveXObject("Microsoft.XMLHTTP");
}

Microsoft's browser (Internet Explorer) uses the MSXML parser for handling XML. MSXML has two different versions, so we need to write code that handles both cases. Thus the code goes as shown below.

Listing 3

var XMLHttp = false;
try
{
  XMLHttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
  try
  {
    XMLHttp = new ActiveXObject("Microsoft.XMLHTTP");
  }
}
if (XMLHttp == false)
{
  XMLHttp = new XMLHttpRequest();
}

The above code tries to create the object in one version of MSXML. If XMLHttp still has its value as false, it tries to create the object in the standard way.

Making a Request

First of all, a JavaScript method is required, which the web page can call. Then we need to do the following.

·         Get the required data from the Web form

·         Build the URL for connecting

·         Open a connection to the server

·         Write a function that the server can run when it is done with its work

·         Send the request

For this the required coding.

Listing 4

function getData() {
// Get the data in the name field from the web form
var name = document.getElementById("name").value;
 
// Proceed only if there is value for the field
if ((name == null) || (name == "")) return;
 
// Build the URL to connect to
var url = "/scripts/getAnswer.php?name=" + escape(name);
 
// Setup a function for the server to run when it's done
XMLHttp.onreadystatechange = showSuggestion;
 
// Open a connection to the server
XMLHttp.open("GET", url, true);
 
// Send the request
XMLHttp.send(null);
}

The first part of the code is simple JavaScript used to catch the form data. Then the code sets a PHP script as the destination for connecting to. First, the URL is specified and then the value of the name field is appended to it. Then the onreadystatechange property has been used to inform the HTTP request object about the JavaScript function to run after getting the response from the server. This function handles further processing of the response sent by the server. To make the actual request, a person needs to call the open() and send() methods of the HTTP request class. The first parameter of the open() function is the request method which can be GET,POST,HEAD or any other method supported by the person's browser. The second parameter is the URL of the page the person requests. The third parameter sets whether the request is asynchronous or not. If TRUE, the execution of the JavaScript function will continue while the response of the server has not yet arrived and if set to false, it will wait for the server response which destroys the very meaning of Ajax i.e. asynchronous data retrieval. Finally, send() is called with a value of null. Since the data to be sent to the server (the value of the name field) has already been added in the request URL, it is not required to send anything in the request. So this triggers the request and the server can do what it has been asked to do.

Handling the Response

First, the function needs to check for the state of the request. If the state has the value of 4, it means that the full server response has already been received and it is OK to continue with the processing.

Listing 5

if (XMLHttp.readyState == 4)
{
// the response has been fully received
}
else
{
// still not ready with the response
}

The full list of the "readystate" values is shown below:

·         0: The request is uninitialized (before open() is called).

·         1: The request is set up, but has not been sent yet (before send() is called).

·         2: The request was sent and is being processed at present.

·         3: The request is being processed; often some partial data is available, but the server has not finished with the response.

·         4: The response is complete and can be used.

The next thing to check is the status code of the HTTP server response. Here it is required to check only the "200" i.e. "OK" response.

Listing 6

if (XMLHttp .status == 200)
{
// you can move on
}
else
{
// there was a problem with the request,
// (example-the response may be a 404 (i.e. Not Found)
}

Now, after checking the state of the request and the HTTP status code of the response, a person needs to decide what to do with the server response. There are two options to access that data:

·         XMLHttp.responseText – will return the server response as a string of text

·         XMLHttp.responseXML – will return the response as an XMLDocument object

The code is as shown:

Listing 7

function showSuggestion()
{
  if (XMLHttp.readyState == 4)
  {
    if (XMLHttp.status == 200)
    {
      var response = XMLHttp.responseText;
      document.getElementById("Suggestion").value = response;
    }
    else
    {
      alert('There was a problem with the request.');
    }
  }
}

It waits for the server to call it with the proper ready state and status. Then it uses the data returned by the server (in this case, the suggestions for the data entered by the user) to set the value of another form field. The result is that the Suggestion field suddenly appears with the suggestions for the name field but without requiring the user to click a submit button.

Finally, here goes the HTML form.

In this form there is a text input for the user to enter data and another placeholder to show the suggestions.

Listing 8

<form>
<p>Name: <input type="text" name="name" id="name" size="25" 
onChange="getData();" /></p>
<p>Suggestion: <span id="Suggestion"></span></p>
</form>

Here, span is used as a placeholder for data retrieved from the web server. When a user writes in a new value for name field, the getData() method is called up and the user is able to view the suggestions without having to click a button. This is what makes Ajax grab the attention of the developers.

Advantages & Disadvantages of Using Ajax

Advantages

Everything has its own merits and demerits, Ajax included.

·         The application seems to become more responsive and interactive as the user gets the response without clicking any buttons.

·         In classic web application, when the web server responds to the web browser with a new page, it may make use of multiple connection threads in order to speed up the process, but this happens for the content only (which is between <body> tags). The CSS as well as the script files present in the head section are transferred using only one connection thread which results in performance degradation. With Ajax, it is required to load only the basic script and CSS files. Rests are requested as content using multiple connections.

·         A big advantage is that the user is not required to keep on waiting and waiting.

·         One more important merit is traffic to and from the server is reduced a considerable amount.

·         If a section of a page encounters any error, other sections do not get affected and the data entered by the user is also not lost.

Disadvantages

·         Ajax application development may lead to increase in development time and cost.

·         The biggest concern is accessibility because all browsers do not completely support Javascript and xmlHttpRequest object.

·         Using Ajax to asynchronously load bits of data into the existing page conflicts the way the users are used to viewing, navigating and creating bookmarks in a modern browser.

·         Another disadvantage lies in the xmlHttpRequest object itself because one can use it to access information from the host that served the “initial page” (due to security reasons).

Where to Use & Where Not to Use Ajax?

Here is a list of a few areas where one should and where one should not use Ajax.

To be used when:

·         The application involves heavy server requests, with multiple web forms that submit data to the server.

·         It is required to display large amount of data in sequence without refreshing the page.

·         Application response time and loading time is a matter of concern.

Not to be used when:

·         Using plain, static HTML pages

·         Users do not interact with the application often.

·         Loading time and bandwidth usage is not a matter of concern.

·         The application is needed to be viewed in older browsers or over various versions of the browser.

·         Time and cost constitute important factors for a project development.

Conclusion

Finally, I would like to conclude that by using Ajax, Internet applications can be made more responsive, more interactive and more user friendly, but at the same time Ajax has its own demerits. So before using it, sit back and think over whether by using Ajax in your applications you are getting rid of your problems or you are running into some other deeper problems.

By Debjani Mallick



User Comments

Title: hai   
Name: bala
Date: 2012-08-28 12:51:06 AM
Comment:
hello how r u
Title: Sundar   
Name: Sundar
Date: 2011-05-29 11:31:33 AM
Comment:
Yes, Ajax Is Really Very Easy. But It Is Very Hard TO Learn
Title: fantastic explanation   
Name: harish Solanki
Date: 2010-12-12 11:57:30 PM
Comment:
it is a great article and after reading this now i am able to understand how ajax works.
Title: Excellent   
Name: clhenter
Date: 2009-09-28 9:48:45 AM
Comment:
Excellent article.
Title: Keeping it simple   
Name: Fat Limbaugh
Date: 2009-05-31 8:36:26 PM
Comment:
You did a good job of keeping it simple and straight forward
Title: all   
Name: jagadish jadhav
Date: 2009-01-10 5:29:08 AM
Comment:
I really thanks to this site owner. it is ever made site for the bignner programmer.
Title: Helpful for Begineers   
Name: Md. Mostafijur Rahman
Date: 2008-08-31 1:26:57 AM
Comment:
Easy to understand..simply nice...
Title: Article on Ajax   
Name: narendra
Date: 2008-07-16 5:50:51 AM
Comment:
Nice article
Title: Good to know about ajax for beginners   
Name: Harikrishna
Date: 2008-07-01 7:28:32 AM
Comment:
This article is very good. Basic idea how Ajax works? simple to understand.
Title: Mind Blowing   
Name: Surendra
Date: 2008-05-22 8:51:38 AM
Comment:
I am new to AJAX and find very comfortable with this article
Title: excellent   
Name: susan
Date: 2008-04-11 9:40:13 PM
Comment:
Wow that was a nice explanation for a newbie to AJAX. Thanks for keeping it simple and easy to understand!
Title: Very Nice   
Name: chirag Panchal (MCA)
Date: 2008-03-28 8:20:34 AM
Comment:
I'm new to AJAX I found this article is very interesting and useful.Thanks a lot.
chirag.bca.mca2007@gmail.com
Title: Really Good   
Name: Prabhakar reddy.D
Date: 2008-02-29 12:49:10 AM
Comment:
I'm new to AJAX I found this article is very interesting and useful.Thanks a lot.
Title: fruitful, really wonderful   
Name: kanagaraj.P
Date: 2008-02-25 4:04:33 AM
Comment:
im very much interested to learn new tech'y. i lve AJAX. I don't knw where to get started, i got tis site. very much informative. Can i get more detailed things abt ajax./.? please help me out to become familiar..
My e mail id:
kanagu.k.raj@gmail.com
Title: Very Useful   
Name: Nandagopal
Date: 2008-02-01 1:01:38 PM
Comment:
I'm new to AJAX I found this article is very interesting and useful.Thanks a lot.
Title: Fruitful Article   
Name: Praveen Kumar emw
Date: 2008-01-29 7:41:22 AM
Comment:
This atricle is very useful.It clears my doubts relating where should AJAX use and where shouldn't.
Thanx a lot.
Title: Ajax   
Name: Ravi
Date: 2007-12-05 12:20:46 PM
Comment:
This Article is good but give example with Asp.Net
.aspx pages
Title: Informative Article   
Name: Ravinder Saini
Date: 2007-11-25 8:25:47 AM
Comment:
Please send me info on AJAX.I need to start developing using ASP.Net with AJAX very soon.


Thanx
Title: EXCELLENT ARTCLE   
Name: asim
Date: 2007-11-22 10:34:49 AM
Comment:
exellent article thanks.
Title: good 2 see   
Name: prashanth
Date: 2007-09-20 7:03:12 AM
Comment:
good 2 all
Title: AJAX - a Detailed Insight   
Name: Balaji
Date: 2007-09-18 11:59:24 PM
Comment:
Hi,
HATS OFF to Debjani Mallick.
Such a detailed insight in a simple language with easy examples..........
I request you to post more and more articles........
Title: Re: security disadvantage?   
Name: Debjani Mallick
Date: 2007-09-18 11:44:50 AM
Comment:
In actual, due to security constraints XMLHttpRequest can only be used to access information from the host that served the initial page. If we need to display information from another server, it is generally not possible within the AJAX paradigm. XMLHttpRequest applies a restriction policy to the same origin. This kind of control will
deny any request made outside actual host,
considering port and protocol.
Title: ...........   
Name: john simpson
Date: 2007-09-18 6:00:02 AM
Comment:
I am new to AJAX and I was wondering for some good information on Ajax. But when i went through your article, i really feel assured and now i can proceed for some AJAX stuffs.

I really feel thankful to you, for publishing such a managed article.
Title: security disadvantage?   
Name: K. Winter
Date: 2007-09-18 4:25:08 AM
Comment:
Thanks for the article, it was useful. Can you shed some more light on the disadvantage that you noted:
"Another disadvantage lies in the xmlHttpRequest object itself because one can use it to access information from the host that served the “initial page” (due to security reasons)."






Community Advice: ASP | SQL | XML | Regular Expressions | Windows


©Copyright 1998-2024 ASPAlliance.com  |  Page Processed at 2024-03-28 8:56:43 PM  AspAlliance Recent Articles RSS Feed
About ASPAlliance | Newsgroups | Advertise | Authors | Email Lists | Feedback | Link To Us | Privacy | Search