Click here to Skip to main content
11,409,922 members (51,375 online)
Click here to Skip to main content

Ajax Tutorial for Beginners: Part 1

, 2 Dec 2008 CPOL
Rate this:
Please Sign up or sign in to vote.
Ajax Tutorial for Beginners: Part 1


Hello everyone. This is my first article on The Code Project. I hope you will get some benefit from it. I have been learning Ajax for the last 5 months and now I want to share my knowledge with you. Please provide feedback on any mistakes which I have made in this article. Believe me guys, your harsh words would be received with love and treated with the top most priority.

I have explained Ajax with XML and JSON in part 2, which you can read here

There are many books and articles out there explaining the 5 Ws (Who, What, Where, When, Why) of Ajax, but I will explain to you in my own simple way. So what is Ajax? The term AJAX (Asynchronous JavaScript and XML) has been around for three years created by Jesse James Garrett in 2005. The technologies that make Ajax work, however, have been around for almost a decade. Ajax makes it possible to update a page without a refresh. Using Ajax, we can refresh a particular DOM object without refreshing the full page.

Background of Ajax

In Jesse Garrett’s original article that coined the term, it was AJAX. The “X” in AJAX really stands for XMLHttpRequest though, and not XML. Jesse later conceded that Ajax should be a word and not an acronym and updated his article to reflect his change in heart. So “Ajax” is the correct casing. As its name implies, Ajax relies primarily on two technologies to work: JavaScript and the XMLHttpRequest. Standardization of the browser DOM (Document Object Model) and DHTML also play an important part in Ajax’s success, but for the purposes of our discussion we won't examine these technologies in depth.

How Ajax Works

At the heart of Ajax is the ability to communicate with a Web server asynchronously without taking away the user’s ability to interact with the page. The XMLHttpRequest is what makes this possible. Ajax makes it possible to update a page without a refresh. By Ajax, we can refresh a particular DOM object without refreshing the full page. Let's see now what actually happens when a user submits a request:


  1. Web browser requests for the content of just the part of the page that it needs.
  2. Web server analyzes the received request and builds up an XML message which is then sent back to the Web browser.
  3. After the Web browser receives the XML message, it parses the message in order to update the content of that part of the page.

AJAX uses JavaScript language through HTTP protocol to send/receive XML messages asynchronously to/from Web server. Asynchronously means that data is not sent in a sequence.

Common Steps that AJAX Application Follows

The figure below describes the structure of HTML pages and a sequence of actions in Ajax Web application:

How Ajax Works

  1. The JavaScript function handEvent() will be invoked when an event occurred on the HTML element.
  2. In the handEvent() method, an instance of XMLHttpRequest object is created.
  3. The XMLHttpRequest object organizes an XML message within about the status of the HTML page, and then sends it to the Web server.
  4. After sending the request, the XMLHttpRequest object listens to the message from the Web server.
  5. The XMLHttpRequest object parses the message returned from the Web server and updates it into the DOM object.

Let's See How Ajax Works in the Code

Let’s start to put these ideas together in some code examples.

form id="form1" runat="server"

input type="text" id="lblTime"

input type="button" id="btnGetTime" value="Get Time" onclick="GetTime();"

  1. From the above code, our DOM object is (input type="text" id="lblTime") which we have to refresh without refreshing the whole page. This will be done when we press the event of a button, i.e. onclick.
  2. In this code, our handEvent() is GetTime() from the above Figure-2 if you take a look at it.

Let's see now how we create an XmlHttpRequest object and make Ajax work for us.

The basic implementation of the XMLHttpRequest in JavaScript looks like this:

var xmlHttpRequest;

function GetTime()
    //create XMLHttpRequest object
    xmlHttpRequest = (window.XMLHttpRequest) ? 
	new XMLHttpRequest() : new ActiveXObject("Msxml2.XMLHTTP");

    //If the browser doesn't support Ajax, exit now
    if (xmlHttpRequest == null)

    //Initiate the XMLHttpRequest object"GET", "Time.aspx", true);

    //Setup the callback function
    xmlHttpRequest.onreadystatechange = StateChange;

    //Send the Ajax request to the server with the GET data
function StateChange()
    if(xmlHttpRequest.readyState == 4)
	document.getElementById('lblTime').value = xmlHttpRequest.responseText;
  1. Now from the above Figure-2 handEvent() i.e. GetTime() creates an XMLHttpRequest object inside it like this:

    //create XMLHttpRequest object
    xmlHttpRequest = (window.XMLHttpRequest) ? 
    	new XMLHttpRequest() : new ActiveXObject("Msxml2.XMLHTTP");
  2. If the browser does not support Ajax, it will return false.

  3. Next we open our connection to the server with our newly created XMLHttpRequest object. Here the Time.aspx page is the page from which we will get XML message that is stored on the Web server.

    //Initiate the XMLHttpRequest object"GET", "Time.aspx", true);
  4. You often hear the term “callback” replace the term “postback” when you work with Ajax. That’s because Ajax uses a “callback” function to catch the server’s response when it is done processing your Ajax request. We establish a reference to that callback function like this. Here StateChange is a function where we update or set a new value to our DOM object, i.e "lblTime".

    //Setup the callback function
    xmlHttpRequest.onreadystatechange = StateChange;

    Let's have a look at our callback function:

    function StateChange()
        if(xmlHttpRequest.readyState == 4)
    	document.getElementById('lblTime').value = xmlHttpRequest.responseText;

    onreadystatechange will fire multiple times during an Ajax request, so we must evaluate the XMLHttpRequest’s “readyState” property to determine when the server response is complete which is 4. Now if readyState is 4, we can update the DOM object with the response message we get from the Web server.

  5. As the request method we are sending is "GET" (remember it is case sensitive), there is no need to send any extra information to the server.

    //Send the Ajax request to the server with the GET data

    In Time.aspx.cs on Page_Load event, write a simple response like this which is our response message:

    Response.Write( DateTime.Now.Hour + ":" + DateTime.Now.Minute + 
    					":" + DateTime.Now.Second );

    That’s it. That’s Ajax. Really.

Key Points to be Remembered in Ajax

There are three key points in creating an Ajax application, which are also applicable to the above Tutorial:

  1. Use XMLHttpRequest object to send XML message to the Web server
  2. Create a service that runs on Web server to respond to request
  3. Parse XMLHttpRequest object, then update to DOM object of the HTML page on client-side


  • 20th November, 2008: Initial version


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


About the Author

Comments and Discussions

QuestionThanks PinmemberMember 1092935120-Apr-15 4:15 
QuestionGood Pinmembersangeetha m20-May-14 2:00 
GeneralMy vote of 5 PinmemberPratik Bhuva13-Sep-13 5:27 
GeneralMy vote of 5 Pinmembersanthudotnet12-Aug-13 21:36 
GeneralMy vote of 4 PinmemberAlireza_136211-Jul-13 16:18 
GeneralMy vote of 5 PinmemberJeyo19908-Jul-13 18:57 
QuestionAjax Pinmembershujaat siddique3-Jun-13 21:24 
QuestionValuble information PingroupPurushotham Agaraharam27-Mar-13 22:05 
GeneralMy vote of 5 PinmemberGirish Balanagu15-Feb-13 2:10 
QuestionGood One PinmemberMember 97442313-Feb-13 21:31 
GeneralMy vote of 5 PinmemberPranit Kothari23-Nov-12 22:45 
GeneralMy vote of 5 Pinmemberiliabest11-Nov-12 3:21 
GeneralMy vote of 4 PinmemberDoppalapudi16-Oct-12 23:38 
GeneralMy vote of 5 Pinmemberyogesh_iitrk21-May-12 0:06 
GeneralMy vote of 5 PinmemberSam Path14-Feb-12 19:41 
QuestionError in text box value is ===full page descripation Pinmembersunilefusion6-Feb-12 23:00 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" ""> <html xmlns=""> <head><title> Display Page </title> <style type="text/css"> .style1 { width: 100%; } </style> </head> <body> <form name="form1" method="post" action="stored procedure.aspx" id="form1">
<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwUKMTI2NTUyOTY5Mg9kFgICAw9kFgICEQ88KwANAGQYAQUJR3JpZFZpZXcxD2dkh9VTZcXuwKpog8qxKuwsijaUri4=" />
<input type="hidden" name="__EVENTVALIDATION" id="__EVENTVALIDATION" value="/wEWCAL/v/+fCALKh45lAoa+9+4HAt+q6NoIAoznisYGArursYYIAtaUz5sCAoXZ9dsDYByDIu4l3TNidOu+VVJUPQPj3/A=" />
Name <input name="text_name" type="text" id="text_name" />
city <input name="text_city" type="text" id="text_city" />
phone_no <input name="text_phone_no" type="text" id="text_phone_no" />
  <input type="submit" name="Button1" value="Save" id="Button1" style="height:25px;width:94px;" />
<input type="submit" name="Button2" value="Retrieve from Stored procedure" id="Button2" /> <input type="submit" name="Button3" value="Retrieve Bye ID" id="Button3" /> <input type="submit" name="Button4" value="Delete_databyID" id="Button4" />
</form> </body> </html>
GeneralMy vote of 3 Pinmembervyashitesh24-Jan-12 3:53 
GeneralMy vote of 4 Pinmemberrameshrathod8-Sep-11 19:16 
GeneralMy vote of 5 PinmemberMd. Touhidul Alam Shuvo26-Jun-11 21:44 
GeneralRe: My vote of 5 Pinmemberbymgdotnet27-Jun-11 22:20 
GeneralIE and caching Pinmemberjadejonge16-May-11 4:48 
GeneralGood Article Pinmemberspvarapu1-Oct-10 21:09 
GeneralMy vote of 3 Pinmemberspvarapu1-Oct-10 21:06 
Generalnice article Pinmembercempreng7-Jul-10 18:17 
GeneralStrange behaviour Pinmembercolmde1-Jul-10 4:48 
GeneralFantastic Pinmembermengmakies18-Mar-10 2:14 
GeneralRe: Fantastic Pinmemberbymgdotnet10-Jun-10 21:24 
GeneralThanks Pinmemberjvanbuskirk18-Dec-09 11:30 
GeneralRe: Thanks Pinmemberbymgdotnet10-Jun-10 21:23 
GeneralGood Article. Pinmembersiddu46565@gmail.com28-Jan-09 22:22 
GeneralRe: Good Article. Pinmemberbymgdotnet3-Feb-09 18:59 
GeneralNice Article. PinmemberGökmen BULUT28-Dec-08 22:56 
GeneralRe: Nice Article. Pinmemberbhupiyujuan30-Dec-08 0:49 
GeneralNice Job Pinmembermichael knopf11-Dec-08 6:20 
GeneralRe: Nice Job Pinmemberbhupiyujuan12-Dec-08 0:10 
GeneralGood Article PinmemberBrij7-Dec-08 22:53 
GeneralRe: Good Article Pinmemberbhupiyujuan8-Dec-08 6:07 
GeneralFormatting PinmemberDmitri Nesteruk3-Dec-08 2:41 
QuestionI must be less than a Beginner Pinmemberbirdog2-Dec-08 6:44 
AnswerRe: I must be less than a Beginner Pinmemberbhupiyujuan2-Dec-08 19:24 
GeneralCheck the response status PinmemberMember 410885723-Nov-08 23:53 
GeneralRe: Check the response status Pinmemberbhupiyujuan24-Nov-08 0:16 
GeneralKey Points to be Remembered in Ajax PinmemberGevorg22-Nov-08 16:37 
GeneralRe: Key Points to be Remembered in Ajax Pinmemberbhupiyujuan22-Nov-08 17:03 
GeneralRe: Key Points to be Remembered in Ajax PinmemberGevorg22-Nov-08 17:45 
GeneralRe: Key Points to be Remembered in Ajax Pinmemberbhupiyujuan22-Nov-08 18:25 
AnswerRe: Key Points to be Remembered in Ajax PinmemberKanedogg0827-Nov-08 12:58 
GeneralRe: Key Points to be Remembered in Ajax Pinmemberbhupiyujuan5-Dec-08 22:35 

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 | Terms of Use | Mobile
Web04 | 2.8.150414.5 | Last Updated 2 Dec 2008
Article Copyright 2008 by bhupiyujuan
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid