Click here to Skip to main content
Click here to Skip to main content

Writing Your First AJAX Application - For Beginners

, 14 Aug 2007
Rate this:
Please Sign up or sign in to vote.
Helloworld AJAX - explaining how Ajax works

Introduction

AJAX or Asynchronous JavaScript and XML is a programming model popularized by Google in early 2005. Ajax technology is based on HTTPrequests,an API which can be used with most of the web browser scripting languages. AJAX is not a new technology. It just provides full control over the response and request data using your JavaScript or any other scripting language supported.

What is HTTPrequests?

HTTPrequests is an API which can be used by web scripting languages like JavaScript, vbscript, etc. HTTPrequests provides a mechanism for transferring the data either in text or XML format between web client and the web server.

In a normal web application, when we submit data from a web browser using get or post method, the browser or the JavaScript will transfer all the data to the web server. Server side script will process this data and the new content is written back directly to the browser. A new page is always generated between the server calls. That means always the browser makes the request and the browser will get back the response. We don't have any control for the request data and the response data. Because of this, to provide a proper view to the end user, we always have to transfer the large data from the web server to the client browser.

This is how a normal web application works:

Screenshot - ajax1.jpg

HTTPrequests eliminate the over burden of reloading the pages between each server call. This concept is originally introduced by Microsoft named as XMLHTTP. XMLHTTP was part of Internet Explorer 5.0 and was accessible using JavaScript, VBScript and other scripting languages supported by Internet Explorer. It contains the method for transferring the data to the web server without submitting the whole page to the server and also an event which is triggered up on getting the response back from the server. Based on the response data obtained from the HTTPrequests, we can use dhtml to change the client browser.

HTTPrequests work as an intermediate agent between the webserver and client browser. It provides total controls to the programmer over the request data and the response data. We just need to use some logic to control the data transfer and to provide a proper display to the user.

Methods of XMLHTTPrequests

Method Description
abort Abort was introduced in Internet Explorer 7. The abort method interrupts an asynchronous operation in progress.
getAllResponseHeaders getAllResponseHeaders method
getResponseHeader Returns the specified response header.
open Assigns method, destination URL, and other optional attributes of a pending request.
send Sends an HTTP request to the server and receives a response.
setRequestHeader Adds custom HTTP headers to the request.

Properties of XMLHTTPrequests

Method Description
onreadystatechange This property sets the method to be called on every state change. This is usually your event handler for the asynchronous callback.
ReadyState This property defines the state of the XmlHttpRequest. Possible values include:

0 Uninitiated
1 Loading
2 Loaded
3 Interactive
4 Complete

When sending the XmlHttpRequest, you will check to see if the readyState is 0 or 4, and in your asynchronous callback handler, you will check to see if the readyState is 4.
responseText This returns the response from the server as a string. If you are only returning one value, this is the way to go because it is much easier than trying to walk the XML DOM.
responseXML This returns the response from the server as an XML document. This is the way to go if you need to return multiple values from your AJAX request. It does require some knowledge of the XML DOM to use, but is quite powerful.
status This returns the HTTP status code from the server such as 200 for OK or 404 for not found.
statusText This returns a string representation of the HTTP status code such as OK for 200 and Not Found for 404

Reference: http://www.dynamicajax.com/fr/XmlHttpRequest_Properties-271_272_302.html

How the HTTP Request Object Works

Your Hello World AJAX Application

To understand how AJAX works as an intermediate agent between the webserver and the browser, we can create a helloworld AJAX application. This example will show how to display the content from text files (located at the webserver) to an HTML input box when the user clicks on the HTML button.

For this, first we will create a simple HTML page "AJAXTEST.html" which contains an input box and two buttons named helloworld1 and helloworld2.

<HTML>
<HEAD>
<Title>AJAX test</Title>
</HEAD>
<body>
<form>
<INPUT id="txtAjax" type="text" name="Text1">
<br>
<button type="button" ID="Button1">Helloworld1</button>
<br>
<button type="button" ID="Button2">Helloworld2</button>
</form>
</body>
</HTML>

Now we will create two text-files named Helloworld1.txt and Helloworld2.txt. We will keep these files in the same folder where our AJAXTEST.html resides

Now we will write the JavaScript which will use the xmlHTTPrequests object to make asynchronous calls to the server to load the data.

This function will demonstrate how to create xmlHTTPrequests and add the state change event handler function.

 function CretexmlHttp()
{  
  try
     {
       XmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
  //Here we will assign ready state change event where we will 
  // handle the response data from the server  
  XmlHttp.onreadystatechange=stateChangeEventHandler;
      }
      //If you have an older version of Internet Explorer, you will have
      // Microsoft.XMLHTTP instead of Msxml2.XMLHTTP
   catch (e)
      {
       XmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
      }
    return XmlHttp;
}

Now we will write a state change event handler function. This event will be triggered by the xmlHTTPrequests when the response is received from the server. This is the place where we can get the response data always.

 function stateChangeEventHandler()
{
//  check whether the data is loaded
if (XmlHttp.readyState==4)
 {  // check whether the status is ok
  if (XmlHttp.status==200)
  {
  document.all ("txtAjax").value=XmlHttp.responseText
  }
 else
 {
  alert ("Error Occurred")
 }
  }
}

In the next step, we will create a function which will accept file name as parameters and will load the textfile from the server.

 function getData(fileName)
{
//call the createxmlhttp function which will create xmlHttp object 
var XmlHttp= CretexmlHttp();
//Assigns method, destination URL, and other optional attributes of a 
//pending request.
XmlHttp.open("GET", fileName,true)
// Sends an HTTP request to the server 
 XmlHttp.send(null)
 return true;
}

Finally to make the code work, we will add all the three functions under the JavaScript tag of our AJAXTEST.html and will call the getData (filename) from the HTML button click event.

The final code will look like this:

<HTML>
<HEAD>
<Title>AJAX test</Title>
<script language="javascript">
function CretexmlHttp()
{  
  try
     {
       XmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
  //Here we will assign ready state change event where we will 
 // handle the response data from the server  
  XmlHttp.onreadystatechange=stateChangeEventHandler;
      }
      //If you have an older version of Internet Explorer, you will have
      // Microsoft.XMLHTTP instead of Msxml2.XMLHTTP
   catch (e)
      {
       XmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
      }
    return XmlHttp;
}
function stateChangeEventHandler()
{
//  check whether the data  is loaded
if (XmlHttp.readyState==4)
  {  // check whether the status is ok
  if (XmlHttp.status==200)
 {
 document.all ("txtAjax").value=XmlHttp.responseText
 }
  else
 {
  alert ("Error Occurred")
 }
  }
}
function getData(fileName)
{
//call the createxmlhttp function which will create xmlHttp object and assign 
var XmlHttp= CretexmlHttp();
//Assigns method, destination URL, and other optional attributes of a 
//pending request.
XmlHttp.open("GET", fileName,true)
// Sends an HTTP request to the server and receives a response
 XmlHttp.send(null)
 return true;
}
</script>
</HEAD>
<body>
  <form>
   <INPUT id="txtAjax" type="text" name="Text1">
   <br>
   <button onclick="getData('Helloworld1.txt')" 
	type="button" ID="Button1">Helloworld1</button>
   <br>
   <button onclick="getData('Helloworld2.txt')" 
	type="button" ID="Button2">Helloworld2</button>
  </form>
 </body>
</HTML>

To test this, you need to place the HTML file in your local web server. And put the two text files under the same folder where the HTML file is placed.

Now when you click on the first button, you will see the content of Helloworld1.txt in the input box and in the next button, click 'Helloworld2.txt' will be displayed.

The following figure illustrates how an AJAX application works:

Screenshot - ajax2.jpg

In AJAX model, the client side JavaScript always controls the transfer of data from the web browser to web server and data back to the browser from the web server. The methods in the HTTP request object always work in a separate thread which enables the user to work on the same page even when a request is sent to the server. Once the response is received from the server, the state change event is triggered and the event handler function can make use of DHTML and JavaScript to provide a proper view of the response data.

You can download the attached sample applications and put all the files under the same folder in your web server. Access the HTML from the browser using the localpath to your webserver.

Browser Compatibility

For using the source code with Firefox, replace CretexmlHttp() with the following code:

Change the CretexmlHttp function in the sample as follows:

function CretexmlHttp()
{ 
try
{
XmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
//Here we will assign ready state change event where we will
// handle the response data from the server 
XmlHttp.onreadystatechange=stateChangeEventHandler;
}
//If you have an older version of Internet Explorer, you will have
// Microsoft.XMLHTTP instead of Msxml2.XMLHTTP
catch (e)
{
try
{
XmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e)
{
//For Firefox
XmlHttp=new XMLHttpRequest();
}

}
return XmlHttp;
} 

Here is a nice article for beginners:

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

rilov
Software Developer (Senior)
Canada Canada
Rilov is working as a software Developer
with maxxam analytics in Canada.
 
rilovpk@gmail.com
 
'I have not failed. I've just found 10,000 ways
that won't work.'
-Thomas Edison

Comments and Discussions

 
GeneralMy vote of 3 Pinmemberdlsantoshkumar29-Mar-11 19:31 
QuestionWhy am I only getting the error alert? PinmemberDanylle A Miller5-Sep-07 18:46 
AnswerRe: Why am I only getting the error alert? Pinmemberrilov6-Sep-07 7:44 
GeneralGood One PinmemberVishu Gurav13-Jul-07 7:24 
GeneralCrossbrowser XMLHttp PinmemberVasudevan Deepak Kumar13-Jul-07 0:26 
GeneralRe: Crossbrowser XMLHttp Pinmemberrilov13-Jul-07 1:22 
GeneralThanks.. PinmemberMichael Sync8-Jul-07 0:03 
JokeRe: Thanks.. [modified] Pinmemberrilov8-Jul-07 3:06 
GeneralRe: Thanks.. PinmemberVasudevan Deepak Kumar13-Jul-07 0:28 
GeneralRe: Thanks.. Pinmemberrilov13-Jul-07 1:28 
GeneralRe: Thanks.. Pinmemberjoyjjjz1-Nov-07 15:27 
GeneralHi Rilov PinmemberInflicted7-Jul-07 13:03 
GeneralRe: Hi Rilov Pinmemberrilov8-Jul-07 3:11 
Questiondoesnt work with firefox? Pinmemberhorsetesticle6-Jul-07 20:25 
AnswerRe: doesnt work with firefox? Pinmemberrilov7-Jul-07 0:23 
GeneralRe: doesnt work with firefox? Pinmemberrilov7-Jul-07 0:42 
QuestionRe: doesnt work with firefox? Pinmemberhorsetesticle7-Jul-07 7:17 
AnswerRe: doesnt work with firefox? Pinmemberrilov7-Jul-07 7:23 
GeneralRe: doesnt work with firefox? PinmemberIlTrips7-Jul-07 10:26 
GeneralRe: doesnt work with firefox? Pinmemberhorsetesticle7-Jul-07 14:12 
GeneralRe: doesnt work with firefox? PinmemberVasudevan Deepak Kumar13-Jul-07 0:29 
GeneralRe: doesnt work with firefox? Pinmemberhaichen13-Jul-07 1:19 
AnswerRe: doesnt work with firefox? PinmemberVasudevan Deepak Kumar13-Jul-07 0:25 
GeneralRe: doesnt work with firefox? Pinmemberrilov14-Jul-07 4:44 
GeneralConfused.. help me plz... [modified] PinmemberMahesh Sapre6-Jul-07 17:40 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web04 | 2.8.140827.1 | Last Updated 14 Aug 2007
Article Copyright 2007 by rilov
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid