Basics of Ajax
page 2 of 5
by Debjani Mallick
Average Rating: This article has not yet been rated.
Views (Total / Last 10 Days): 39967/ 92

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();

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();
  // 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;
  XMLHttp = new ActiveXObject("Msxml2.XMLHTTP");
catch (e)
    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"GET", url, true);
// Send the request

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
// 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
// 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;
      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

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

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.

View Entire Article

User Comments

Title: hai   
Name: bala
Date: 2012-08-28 12:51:06 AM
hello how r u
Title: Sundar   
Name: Sundar
Date: 2011-05-29 11:31:33 AM
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
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
Excellent article.
Title: Keeping it simple   
Name: Fat Limbaugh
Date: 2009-05-31 8:36:26 PM
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
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
Easy to understand..simply nice...
Title: Article on Ajax   
Name: narendra
Date: 2008-07-16 5:50:51 AM
Nice article
Title: Good to know about ajax for beginners   
Name: Harikrishna
Date: 2008-07-01 7:28:32 AM
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
I am new to AJAX and find very comfortable with this article
Title: excellent   
Name: susan
Date: 2008-04-11 9:40:13 PM
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
I'm new to AJAX I found this article is very interesting and useful.Thanks a lot.
Title: Really Good   
Name: Prabhakar reddy.D
Date: 2008-02-29 12:49:10 AM
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
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:
Title: Very Useful   
Name: Nandagopal
Date: 2008-02-01 1:01:38 PM
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
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
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
Please send me info on AJAX.I need to start developing using ASP.Net with AJAX very soon.

Name: asim
Date: 2007-11-22 10:34:49 AM
exellent article thanks.
Title: good 2 see   
Name: prashanth
Date: 2007-09-20 7:03:12 AM
good 2 all
Title: AJAX - a Detailed Insight   
Name: Balaji
Date: 2007-09-18 11:59:24 PM
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
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
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
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-2020  |  Page Processed at 2020-06-01 4:53:07 AM  AspAlliance Recent Articles RSS Feed
About ASPAlliance | Newsgroups | Advertise | Authors | Email Lists | Feedback | Link To Us | Privacy | Search