1. PREFACE
This tutorial is free only for educational purpose. This tutorial is not full; it helps you to just
know the subject. This is good to start a beginning.
We have collected study material also from out-sources which is not meant for any sales
value. This tutorial is also not publishing on any commercial web site, society or any other
area where it shows commercial.
Shweta SofTech India erstwhile Shim SofTech India is established on 26th Jan’2006 for
encouraging free I.T. education in India. We hope you will get a worth from this book.
For any further query please write to us: info@shwetasoftech.com
With many thanks,
Shimona Arora
shim@shimsoftech.com
2. AJAX: ........................................................................................................................................ 1
WHAT STANDS FOR AJAX: ........................................................................................................... 2
AJAX – ENABLED WEB-PAGE: ARCHITECTURE ................................................................................ 3
AJAX – LIFE CYCLE ..................................................................................................................... 3
AJAX – WEB STANDARD .............................................................................................................. 4
WHEN DO I START USING AJAX? ..................................................................................................... 4
HOW DOES AJAX WORK? ............................................................................................................... 4
THE READYSTATE PROPERTY .........................................................................................................5
THE RESPONSETEXT PROPERTY......................................................................................................5
AJAX - SENDING A REQUEST TO THE SERVER ...............................................................................5
CROSS-BROWSER ISSUES ..................................................................................................................5
EXERCISE:..........................................................................................................................................6
AJAX: IMPLEMENTATION ......................................................................................................... 7
SIMPLE LOGIN ACTIVITY WITHOUT USE OF AJAX:..........................................................................7
APPLICATION WITH AJAX: ............................................................................................... 10
LOGIN-AJAX.HTML ......................................................................................................................... 10
CLIENTACTION-AJAX.JS................................................................................................................ 11
GETID.ASP....................................................................................................................................... 12
EXPLANATION OF AJAX APPLICATION ....................................................................................... 13
USING, AJAX, YOU CAN ALSO SOLVE ALL OTHER PROBLEMS RELATED TO DATABASES, XML
ETC.EXERCISE: ............................................................................................................................... 13
EXERCISE:....................................................................................................................................... 14
3. 1 AJAX-Learning Tutorial
AJAX:
When we started this topic many questions revolved around our minds. What is Ajax? What it
does? Why we need to use it? And many more.
We are here to solve all those questions. Lets starts with a simple step. First to know exactly
what is it? I will tell you the full meaning of the Ajax in next lines but now let me explain
that:
Whenever we need some information at client side, what is happened or what did we do? In
Simple words, we just send request from browser to server and get the response. Yes, this is
all known as round trip. But, did you notice in this, what?
Generally, when we sent a request to server from browser our entire page did get refresh and
each and every page element reload the page. Or in other words lets take it in following
examples:
<head>
<title>Login.html</title>
</head>
<body>
<form name="myForm">
<table>
<tr>
<td><b>Login Id : </b> <input type="text" name="myLogin" /></td>
</tr>
<tr>
<td><b>Password: </b> <input type="text" name="myPass" /></td>
</tr>
</table>
<p>
<input type="submit" name="myDetails" value="Login" />
</p>
</form>
</body>
</html>
The above html page looks like as:
Shim SofTech India (email: info@shimsoftech.com)
4. AJAX-Learning Tutorial 2
Now, what happens when user enter Login id simply nothing happens until he or she submit
the request by pressing Login button. As soon as login button presses a request to server for
checking the existence of the Login Id in databases or in any other source where it is located.
It means whenever login button press, a request passes to the server and response gets at
browser site by refreshing or reloading the entire page.
Think about that page, form which contains numerous elements present on it. Isn’t it slow
down the speed of the web or page on every request? Because, every time page will be
reloaded its element.
To redeem this issue we use AJAX. With the help of Ajax we don’t need to refresh entire
page to fulfill our request.
WHAT STANDS FOR AJAX:
The brief terminology of the web page is cleared, also the request and response is understand.
Now, let’s start with the meaning of AJAX:
AJAX: ASYNCHRONOUS JAVASCRIPT AND XML
To define it more deeply lets first understand the Synchronous and Asynchronous.
Suppose, you want to know the existence of entered login-id (sometimes, user-id and
login-id behaves synonymous but in practically user-id is the
identification of the user who is permit to obtain or use the
services to a particular unit or page, in the other hand Login-id
ensures the entrance of a particular Login-id holder but it doesn’t
mean that he or she may entitle to obtain the services. Because in
some cases where security matters upto its hike, different kinds of
user-id’s provided to different persons under same login-id. Suppose,
you have a card to enter in office premises, you punch the card it
means you logins then push back the card and enter your personal PIN
or identification number with your password, all this is about Login-
Id and User-ID) in a registration form. It requires when new user want to register for the
services and he or she fills the registration form. At this stage what happens? Normally,
request goes to server and response retrieve to browser about the existence of the entered
Login Id. Our entire rest action or work is blindly depend upon this action, it means we are
unable to do or process an further step until we retrieve or get the response from server. This
task is known or called as Synchronous. While in the other hand the contents of entire page or
some part-contents of page need the same process but out other task or work is not affect from
this, is called asynchronous task(s).
In general, simple and in raw words you can compare both with the two way and one-way
communication. In one we have to wait the response to go ahead for next step while in other
we may proceed for the further step.
Shim SofTech India (email: info@shimsoftech.com)
5. 3 AJAX-Learning Tutorial
With the keen light of above discussion, now we are able to declare the exactly what is
AJAX?
AJAX is a web technology which is favorable to dynamic and rich web control/elements. It is
a combination of JavaScript and XML, favoring asynchronously communication.
AJAX – ENABLED WEB-PAGE: ARCHITECTURE
It’s a technology and not a new to developers It is using from 2005 in Google services like
Google maps and Google suggests.
With AJAX, your JavaScript can communicate directly with the server, using the JavaScript
XMLHttpRequest object. With this object, your JavaScript can trade data with a web server,
without reloading the page.
AJAX uses asynchronous data transfer (HTTP requests) between the browser and the web
server, allowing web pages to request small bits of information from the server instead of
whole pages.
Ajax enables a new architecture. The important parts of this architecture are:
1. Small Server Side Events: Now components in a web application can make small
requests back to a server, get some information, and tweak the page that is viewed by
changing the DOM. No full page refresh.
2. Asynchronous: Requests posted back to the server don’t cause the browser to block.
The user can continue to use other parts of the application, and the UI can be updated
to alert the user that a request is taking place.
3. onAnything: We can talk back to a server based on almost anything the user does.
Modern browsers trap most of the same user events that the operating system allows:
mouse clicks, mouse overs, keypresses, etc. Any user event can trigger an
asynchronous request.
AJAX – LIFE CYCLE
1. User makes initial request against a given URL
2. Server returns original HTML page
3. Browser renders page as in-memory DOM tree
4. User activity causes subsequent request against another URL asynchronously, leaving
existing DOM tree untouched
5. Browser returns data to a callback function inside the existing page
6. Browser parses result and updates in-memory DOM with the new data, which is then
reflected on screen to the user (the page is redrawn, but not "refreshed")
Imp: The AJAX technique makes Internet applications smaller, faster and more user-friendly. AJAX is a browser technology independent
of web server software.
Shim SofTech India (email: info@shimsoftech.com)
6. AJAX-Learning Tutorial 4
AJAX – WEB STANDARD
AJAX is based on the following web standards:
• JavaScript
• XML
• HTML
• CSS
The web standards used in AJAX are well defined, and supported by all major browsers.
AJAX applications are browser and platform independent.
WHEN DO I START USING AJAX?
As already mentioned above that Ajax is very easy and based on Web Standard technology.
So, if you know or have the idea of JavaScript, Xml, Html, CSS then you can start Ajax today
from now.
If you are unaware from the above technologies then no need to be depressed just take a
beneath sitting for above topics and return back here to learn and know about the exiting and
more powerful technology called AJAX.
HOW DOES AJAX WORK?
It’s the first question in my mind when I have started to read Ajax. As it is already discussed
that this is a Technology of web based so, it also works same as other technologies work.
Let’s start in simple terminology: to do start any web application we need following(s):
• Platform or Form to enter user data
• Server side scripting language
• Client Side scripting language
In previous mentioned example titled login.html provides us a form to enter information.
Now for other two i.e. sever side and client side languages first, we need to understand
following in more details:
In traditional JavaScript coding, if you want to get any information from a database or a file
on the server, or send user information to a server, you will have to make an HTML form and
GET or POST data to the server. The user will have to click the "Submit" button to send/get
the information, wait for the server to respond, and then a new page will load with the results.
Because the server returns a new page each time the user submits input, traditional web
applications can run slowly and tend to be less user-friendly.
With AJAX, your JavaScript communicates directly with the server, through the JavaScript
XMLHttpRequest object With an HTTP request, a web page can make a request to, and get a
response from a web server - without reloading the page. The user will stay on the same page,
and he or she will not notice that scripts request pages, or send data to a server in the
background.
Shim SofTech India (email: info@shimsoftech.com)
7. 5 AJAX-Learning Tutorial
By using the XMLHttpRequest object, a web developer can update a page with data from the
server after the page has loaded!
The XMLHttpRequest object is supported in Internet Explorer 5.0+, Safari 1.2, Mozilla 1.0 /
Firefox, Opera 8+, and Netscape 7.
The readyState Property
The readyState property holds the status of the server's response. Each time the readyState
changes, the onreadystatechange function will be executed. Here are the possible values for
the readyState propery:
State Description
0 The request is not initialized
1 The request has been set up
2 The request has been sent
3 The request is in process
4 The request is complete
The responseText Property
The data sent back from the server can be retrieved with the response Text property. This
property assures the responded data of our request.
AJAX - Sending a Request to the Server
To send off a request to the server, we use the open() method and the send() method.
The open() method takes three arguments. The first argument defines which method to use
when sending the request (GET or POST). The second argument specifies the URL of the
server-side script. The third argument specifies that the request should be handled
asynchronously.
The send() method sends the request off to the server.
Cross-Browser Issues
The web page painted with Ajax technology at least one rather severe cross-browser
imitation. The way it initializes the XMLHttpRequest object will only function on Mozilla
1.0+ and Safari 1.2+; it does not function on Internet Explorer. On IE 5.0+, the way to create
it is (discussed in following example:
Shim SofTech India (email: info@shimsoftech.com)
8. AJAX-Learning Tutorial 6
var xmlHttp=null;
try
{
// Firefox, Opera 8.0+, Safari
xmlHttp=new XMLHttpRequest();
}
catch (e)
{
// Internet Explorer
try
{
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
}
return xmlHttp;
The simple method is to obey the Try-Catch rule to initiate the same. In we have declared a
variable named xmlHttp and then creating an object of XMLHttpRequest() using try-catch
block. This is the universal block which is used in everywhere Ajax use.
Exercise:
Let’s revise
1. What is Ajax?
2. How Ajax web based Technology?
3. Write few line son Ajax Architecture defining life cycle of an Ajax web page
4. How does Ajax work?
5. How we can detect browser using try-catch bock?
6. Define four ready states of Ajax.
7. What are send() and open(0 method(s)?
8. What are cross-browsers issue?
9. What do you mean by round trip?
10. Define Login-Id and User-Id myth
Shim SofTech India (email: info@shimsoftech.com)
9. 7 AJAX-Learning Tutorial
AJAX: IMPLEMENTATION
In this head we will consider some practical exercise which favoring implementation of the
Ajax:
Our entire topic is depends upon the Registration and Login issues:
Simple Login activity without use of Ajax:
Consider our login.html example; let’s modify it with the use of JavaScript:
Login.html
<head>
<title>Login.html</title>
<script src="clientaction.js">
</Script>
</head>
<body onLoad="set(this.form);">
<form name="myForm">
<table>
<tr>
<td><b>Login Id : </b> <input type="text" name="myLogin"
size="40" onBlur="checklen(this.form);" /></td>
</tr>
<tr>
<td><b>Password: </b> <input type="text" name="myPass"
size="40" /></td>
</tr>
</table>
<p>
<input type="submit" name="myDetails" value="Login"
onClick="verify(this.form);" />
</p>
</form>
</body>
</html>
Shim SofTech India (email: info@shimsoftech.com)
10. AJAX-Learning Tutorial 8
Clientaction.js
// JavaScript Document
//File Name - clientaction.js
<!-- The function verify() chekd whetehr appropriate information -->
<!-- filled in all the elements. I any elements is left empty, an
alert() box-->
<!--is displayed information the user to fill in the empty element.
the code-->
function verify(form)
{
for (i=0; i<=1;i++)
{
if (document.forms[0].elements[i].value=="")
{
alert("Please fill in the " +
document.forms[0].elements[i].name +" field");
document.forms[0].elements[i].focus();
return(false);
}
}
return(true);
}
<!--Sets the focus on the first element when the form loade-->
function set(form)
{
document.forms[0].elements[0].focus()
}
<!--he function checklen() checks that the length of name and-->
<!--email address does not exceed 30 character-->
function checklen(form)
{
for(i=0;i<=1;i++)
{
val=document.forms[0].elements[i].value;
len=val.length;
if(len>30)
{
alert("Value exceeds 30 characters");
document.forms[0].elements[i].value="";
document.forms[0].elements[i].focus();
}
}
}
Shim SofTech India (email: info@shimsoftech.com)
11. 9 AJAX-Learning Tutorial
With the help of above change, we can just enable client interaction but till now our problem
is arisen as the same.
Only some or fewer errors made at browser side will be displayed. But our main motive is
asynchronous communication. The above is done when we submit the form. It means that the
whole document first submit and then gets the response from the server. It will take time.
Now, not wasting the time lets start our Ajax application.
Shim SofTech India (email: info@shimsoftech.com)
13. 11 AJAX-Learning Tutorial
clientaction-ajax.js
var xmlHttp
function showID(str)
{
if (str.length==0)
{
document.getElementById("txtid").innerHTML="";
return;
}
xmlHttp=GetXmlHttpObject()
if (xmlHttp==null)
{
alert ("Your browser does not support AJAX!");
return;
}
var url="getid.asp";
url=url+"?q="+str;
url=url+"&sid="+Math.random();
xmlHttp.onreadystatechange=stateChanged;
xmlHttp.open("GET",url,true);
xmlHttp.send(null);
}
function stateChanged()
{
if (xmlHttp.readyState==4)
{
document.getElementById("txtid").innerHTML=xmlHttp.responseText;
}
}
function GetXmlHttpObject()
{
var xmlHttp=null;
try
{
// Firefox, Opera 8.0+, Safari
xmlHttp=new XMLHttpRequest();
}
catch (e)
{
// Internet Explorer
try
{
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
}
return xmlHttp;
}
Shim SofTech India (email: info@shimsoftech.com)
14. AJAX-Learning Tutorial 12
getid.asp
<%
response.expires=-1
dim a(36)
'Fill up array with names
a(1)="Anu"
a(2)="Mohan"
a(3)="Anil"
a(4)="Sunil"
a(5)="Vinita"
a(6)="Subha"
a(7) ="Gaurav"
a(8)="Neetu"
a(9)="Rachita"
a(10)="Inga"
a(11)="Ricky"
a(12)="Rekha"
a(13)="Linda"
a(14)="Nina"
a(15)="Ophelia"
a(16)="Petunia"
a(17)="Amanda"
a(18)="Raquel"
a(19)="Cindy"
a(20)="Doris"
a(21)="Eve"
a(22)="Evita"
a(23)="Sunniva"
a(24)="Tove"
a(25)="Unni"
a(26)="Violet"
a(26)="Liza"
a(27)="Elizabeth"
a(28)="Ellen"
a(29)="Wenche"
a(30)="Vicky"
a(31)="Shimona"
a(32)="Swati"
a(33)="Arun"
a(34)="Shikha"
a(35)="Shweta"
a(36)="Anu"
'get the q parameter from URL
q=ucase(request.querystring("q"))
'lookup all hints from array if length of q>0
if len(q)>0 then
hint=""
for i=1 to 36
if q=ucase(mid(a(i),1,len(q))) then
if hint="" then
hint=a(i)
else
hint=hint & " , " & a(i)
end if
end if
next
end if
if hint="" then
response.write("<b>This Login Id is invalid or doesn't exist</b>")
Shim SofTech India (email: info@shimsoftech.com)
15. 13 AJAX-Learning Tutorial
else
response.write("<b>Available user(s): </b>" & hint)
end if
%>
Explanation of Ajax Application
Above example is explained as follow:
1. A Form is created, in which login id is entered
2. In the event of keyup of the field showed() function calls by passing field’s value
3. In the function we have confirmed the browser and then send the request using open()
and send () method(s).
4. Get the text by checking onreadystatechange.
5. In the other hand in file getid.asp which is written in server side scripting language,
we have declared an array of some id’s.
6. Now, as soon as we write in the Login Id field, available logins display in the bottom
of the form and if not available then message appears.
7. This all is done using asynchronous communication.
Using, Ajax, you can also solve all other problems related to databases, xml etc.
Shim SofTech India (email: info@shimsoftech.com)
16. AJAX-Learning Tutorial 14
Exercise:
Implement ajax in following(s):
1. Create a registration form which contains Login-ID, First Name, Last Name,
Password, Retype Password field(s). During the registration confirm existence of
entered Login-Id. The database stores in file user.mdb
2. In continuation to above create a Login-form which permits login-id which is stored
in user.xml file (the login id’s are same as stored in user.mdb file). Here using Ajax,
compare the password. On successful login show the welcome window showing the
Full Name and id of the user.
3. Create a text file named collection.txt which contains the information of
abbreviations, like- Ajax: Asynchronous JavaScript and Xml, HTML: ypertext
MarkUp Language, ASP: Active Server Pages, PHP: PHP Hypertext Preprocessor
etc. Create a form where user enter any words then retrieve the information related to
that word (if exists), if information of entered word is not found in the collection ask
user to enter the proper definition of that words by showing Id and definition field(s).
remember ID and definition field are like AJAX (ID) and Asynchronous JavaScript
and Xml (definition).
4. Recreate above application using database(s) instead of text file(s).
To obtain the full collection of codes please write to us: infor@shwetasoftech.com under
subject: Ajax-examples. These all are free and anyone can use these examples as these ae
meant for only educational purpose.
Shim SofTech India (email: info@shimsoftech.com)