AspAlliance.com LogoASPAlliance: Articles, reviews, and samples for .NET Developers
URL:
http://aspalliance.com/articleViewer.aspx?aId=1395&pId=-1
Basics of Ajax
page
by Debjani Mallick
Feedback
Average Rating: This article has not yet been rated.
Views (Total / Last 10 Days): 40269/ 136

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



©Copyright 1998-2019 ASPAlliance.com  |  Page Processed at 2019-05-24 7:20:51 PM  AspAlliance Recent Articles RSS Feed
About ASPAlliance | Newsgroups | Advertise | Authors | Email Lists | Feedback | Link To Us | Privacy | Search