Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / web / HTML

Writing Your First AJAX Application - For Beginners

3.17/5 (21 votes)
14 Aug 2007CPOL6 min read 1   877  
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
<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.

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

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.

JavaScript
 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.

JavaScript
 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
<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:

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)
{
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)