AJAX Tutorial
AJAX Tutorial
AJAX Tutorial
Introduction to AJAX
Foreword:
This tutorial provides an introduction to AJAX; initially by explaining the different
associated concepts and then presenting how to practically use AJAX in simple
applications.
Basic Requirements:
You should have some basic knowledge about HTML/XTML and Javascript before
you start with AJAX .
AJAX is simply about JavaScript on the client (web browser) communicating with
the server using XML. It is based on JavaScript and HTTP requests.
By using AJAX, better, faster and easier to use web applications can be created.
AJAX is not a new programming language it just introduces a new method of
using the existing language standards.
The Ajax web model is based on the traditional web model with changes to the
transmitted message on the web server and the web browser. The following
diagram presents the
AJAX web model.
In the figure,the current HTML page displayed on the web browser has three parts.
The two purple parts don’t need to be updated; only the yellow part needs to be.
Submitting a Request
1. Web browser requests for the content of just the part of the page that it needs.
2
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.
Benefits of AJAX
• AJAX brings to web applications new characteristics that are not available
as standard in traditional web applications.
• Continuous uploading,time is not wasted while waiting for page redraws and reloads
• Real-time updates, certain parts of the web pages are directly updated without
requiring the whole page to update.
• Greater graphical interaction similar to desktop applications – drag and drop
• Standard mechanism for the client to interact with the server and only send small xml
fragments.
Role of JavaScript
•
• The HTML DOM is the Document Object Model for HTML. The HTML DOM defines a
standard set of objects for HTML and a standard way to access and manipulate
HTML documents
•
• The HTML DOM views HTML documents as a tree structure of elements. All
elements, along with their text and attributes, can be accessed and manipulated
through the DOM tree
•
• The HTML code below shows DOM Body,Form and Input objects. The Input objects
are embedded in the Form and the Form is embedded in the Body object
3
<html>
<head></head>
<body>
<form id=”loginForm”>
<input type=”text” id=”userName”/>
<input type=”submit” id=”login” value=”Login”/>
</form>
</body>
</html>
The languages that can be used within the HTML DOM to access DOM objects are
Java,JavaScript,and VBScript
Example:
A JavaScript function will be added into the HTML code above to handle the
onClick event of the Login button. As the user clicks the button,the notification
message:“The name is required field and can not be empty” will occur,if the user
did not type in his name. The code as in following:
<html>
<head>
<script type=”text/javascript”>
function validateUser()
{
name= document.getElementById(“userName”).value;
if (name == ””)
{
alert(“The name is required field and can not be empty”);
}
}
</script>
</head>
<body>
<form id=”loginForm”>
<input type=”text” id=”userName”/>
<input type=”submit” id=”login” value=”Login” onClick=”validateUser()”/>
</form>
</body>
</html>
4
Ways to submit a request to the web server
In the traditional web model,HTML Form elements are used to submit request to web server. The
HTML code below is an example of an HTML form:
The data of the sent message is combined with the data in the html form. In the
above code, the content of the message is the value of the userName textbox.
After submitting the request, the web browser then receives a new HTML page
from the web server
In the Ajax web model, there is another way, by using the XMLHttpMessage object
to communicate with web server. The XMLHttpMessage object is used to
send/receive messages to and from the web server.
AJAX Application
The figure below describes the structure of HTML pages and a sequence of actions
in Ajax web application.:
5
· XML message - message transferred between XMLHttpRequest object and web
server is under XML format
Ajax web application follows the sequential steps below; the actions are also mapped
from the above figure:
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
For a demonstration of the steps, a code example is presented in the next section.
In this section,an example for Ajax web application is created step by step. The
example is based on a simple login page that validates the username entered in.
Requirements:
· The web application has a Login page containing username and password
textboxes
· When the user types in his name, he will receive notifications about the status of
the current value in the username textbox
· If the current value is a beginning part of the string “VisualBuilder”,the user will
receive a green notification “Continue..”
· If the current value is not a beginning part of the string,user will receive a red
notification - “Invalid input name”
· If the current value is equal to the string, user will receive a blue notification
“Valid input name”
This web application includes only a web page and a service running on web
server.
The web page is HTML code with the embedded JavaScript functions:
· ValidateUser() to catch the user’s typing event on the username textbox and to
send/receive the XML message
· UpdateDOM() to parse the received message and update the status on the HTML
page.
The service running on the web server has the role to listen to the request from
the web browser then send back an appropriate XML response.
The diagram below describes the steps above in a sequence of methods invoked:
6
There are three key points in creating an Ajax application,which are also
applicable to this example:
When the user is typing in the username textbox,the onKeyUp event is sent and
the JavaScript function validateUse() will be invoked,as written in following:
There are two ways of creating an instance of XMLHttpRequest object. They deal
with the different kinds of browser,one for Internet Explorer and one for the other
browsers such as Mozilla,Safari.
7
oXMLRequest.open("GET",strValidationServiceUrl,true);
oXMLRequest.onreadystatechange = updateDOM;
oXMLRequest.send(null);
Secondly, on the server-side, within Java web application, we use one Java Servlet
as service running on web server. This servlet is to validate user name. It has the
doGet method to service http GET method:
public void doGet(HttpServletRequest oRequest,HttpServletResponse oResponse)
throws IOException,ServerException
{
oResponse.setContentType("text/xml");
oResponse.setHeader("Cache-Control","no-cache");
if (“VisualBuilder”. indexOf(strUserName) == 0)
{
if (“VisualBuilder”.equals(strUserName))
{
oResponse.getWriter().write(“Valid”);
}
else
{
oResponse.getWriter().write(“Continue”);
}
}
else
{
oResponse.getWriter().write(“Invalid”);
}
The doGet checks user name posted by the client. If the is used name as a
8
beginning part of “VisualBuilder”,the value of text response will be “Continue”,this
means user is typing correctly. If the name is equal to “VisualBuilder”,the
response will be “Valid”. However,in other cases,the response will be “Invalid”. At
the last,the doGet sends back this response to client.
Eventually,after receiving the response,the DOM object of the client html page will
be updated. We do that in the updateDOM method:
function updateDOM()
{
if (oXMLRequest.readyState == 4)
{
if (oXMLRequest.status == 200)
{
strStatus = oXMLRequest.responseText
var statusDiv =
document.getElementById("status");
if (document.all)
{
statusDiv = document.all["status"];
}
if (strStatus == "Valid")
{
statusDiv.innerHTML = "<div style='color:green'> Valid user</div>";
}
else if (strStatus == "Invalid")
{
statusDiv.innerHTML = "<div style='color:red'> Invalid
user</div>";
}
else if (strStatus == "Continue")
{
statusDiv.innerHTML = "<div style='color:green'> Continue..</div>";
}
}
}
The response message can be under text or xml format. In this method,parsing
xml message is very simple: by getting the text value of the responseText
property. Still there is another way to get content of response,by parsing value of
the responseXML property. You could refer to the Ajax example for parsing xml for
it.
9
Screen shots of running an AJAX example
10
To get a valid user entered type'VisualBuilder':
This web example shows how to search books. When the user types into the
category textbox,a list of book categories is received that have names near to
value of the category textbox. If the value of the category textbox is found,the
books textbox will display all books of this category
In this example, we used HTTP messages between the web browser and web
server as XML messages
11
There are three key points in using with:
· In client-side,build and send XML message
· In server-side,parse received XML message and build to respond a new XML
message
· In client-side,parse the response XML message and update to DOM.
The doPost() method of the servlet is to examine request in POST HTTP method
from client,it looks like:
This code shows that when each POST request is caught,the servlet parses to get
value of the category passed by the client and will look up for the list of books
based on the given category,then respond it.
·Set response message as XML format instead of TEXT as in the first example
·Build response XML message
<book_response>
<suggestion></suggestion>
<books>
<book></book>
<book></book>
<book></book>
</books>
</book_response>
12
this. Its code includes two parts: update suggestion and books
The section code below is to get the root document of the XML message:
In order to get and update suggestion using the XML structure shown above,we do
as:
We update the book list similar to the given suggestion. However,we should
notice the way to get data from the tree node.
13
For demonstration of running this application,you could refer to the Example of
Ajax section
How to create?
Currently,there are two ways to create object based on the browser provider:
Object methods
Method Description
abort() Stops the current request
getAllResponseHeaders() Returns complete set of headers (labels
and values) as string
getResponseHeader(“headerLabel”) Returns string value of a single header
label
open(“method”,“URL”,[. This method is used to sets up a new
asyncFlag[,”userName” request to server.
[,”password”]]])
Its parameters specify destination UR
,sending method and other optional
attributes of a pending request
14
Property Description
onreadystatechange Event handler for an event that fires at
every state change
ReadyState Object status integer:
- 0 = un-initialized
- 1 = loading
- 2 = loaded
- 3 = interactive
- 4 = complete
responseText The text that server sends back to respond
to a request.
responseXML DOM-compatible document object of data
returned from server
Status Numeric code returned by server
15
In this model,the client (browser or client application) makes a request to the
server then waits until it receives a response from the server before doing
anything.
This process consumes unnecessary time.
Suitability:
The synchronous model is not suitable with the kind of client application that
often does interactions to the server. Especially within a web application because
it makes them very slow.
With asynchronous model,the client application does not consume much of the
user’s time making him wait for the response. Therefore,the user feels in real-time
while interacting. The sequence diagram below shows the functioning of an
asynchronous model:
This diagram shows that after sending the request,the client can do something
else instead of wasting his time waiting for the response and doing nothing.
oXMLRequest.open(strHttpMethod,strValidationServiceUrl,bAsynchronous);
AJAX Frameworks:
There are many frameworks for Ajax,like JSF and Struts frameworks for
Servlet/JSP,developed to help developers more clearly and easily to write an Ajax
project. In this section we will review several remarkable Ajax frameworks:
16
- Ajax JSP Tag Library
- Ajax.Net
- OpenRico
- Prototype
- Sarissa
Ajax.Net:
Ajax.Net is a library enabling various kinds of access from JavaScript to server-
side.Net. It is able to access session data from JavaScript without source code
changed on server-side. It also provides full class support for the returned values
on the client-site’s JavaScript including DataTable,DataSet,DataView,Arrays and
Collections
OpenRico:
Rico provides a very simple interface for registering Ajax request handlers as well
as HTML elements or JavaScript objects as response objects. It also provides
interfaces for enabling web application to support drag and drop.
Prototype
Prototype is a JavaScript framework including a solid Ajax library and a toolkit to
simplify its use.
Sarissa
Sarissa is a JavaScript API that summarizes XML functionality in browser-
independent calls. It supports a variety of XML technologies,including XPath
queries,XSLT,and serialization of JavaScript objects to XML
17
18