What Is Ajax - Ravi Thanki

What Is Ajax?
Ajax stands for Asynchronous JavaScript and XML. Ajax isn’t a technology; it mixes
well-known programming techniques in an uncommon way to enable web developers to
build Internet applications with much more appealing user interfaces. When using
desktop applications, we expect the results of our work to be made available immediately
and without us having to wait for the whole screen to be redrawn by the program. While
using a spreadsheet such as Excel, for instance, we expect the changes we make in one
cell to propagate immediately through the neighboring cells while we continue to type,
scroll the page, or use the mouse.
Unfortunately, this sort of interaction has rarely been available to users of web-based
applications. Much more common is the experience of entering data into form fields,
clicking on a button or link, and then sitting back while the page slowly reloads to exhibit
the results of the request. In addition, we often find that the majority of the reloaded page
consists of elements that are identical to those of the previous page and that have
therefore been reloaded unnecessarily such as background images, logos, and menus.
Ajax gives a solution to this problem. By working as an extra layer between the browser
and the web server, Ajax handles server communications in the background, submitting
server requests and processing the returned data. The results may then be integrated into
the page being viewed, without that page needing to be refreshed or a new one loaded.
In Ajax applications, such server requests are not necessarily synchronized with user
actions such as clicking on buttons or links. A well-written Ajax application may already
have asked of the server, and received, the data required by the user perhaps before the
user even knew he wanted it. This is the meaning of the asynchronous part of the Ajax
acronym.
The parts of an Ajax application that happen "under the hood" of the browser, such as
sending server queries and dealing with the returned data, are written in JavaScript, and
XML is a means of coding and transferring formatted information used by Ajax to
efficiently transfer data between server and client.
What makes AJAX Useful?
AJAX development is a big step towards web development: instead of having to send
everything to the server in a single, huge mass, then wait for the server to send back a
new page for rendering, web developers can communicate with the server in smaller
chunks, and selectively update specific areas of the page based on the server’s responses
to those requests. This is where the word asynchronous in the AJAX originated.
It’s is easy to understand the idea of an asynchronous system by considering its
opposite—a synchronous system. In a synchronous system, everything occurs in order. If
a car race was a synchronous system, it would be a very dull affair. The car that started
first on the grid would be the first across the finish line, followed by the car that started
second, and so on. There would be no overtaking and if a car broke down, the traffic
1
behind would be forced to stop and wait while the mechanics made their repairs.
Traditional web applications use a synchronous system: you must wait for the server to
send you the first page of a system before you can request the second page.
Traditional Web Application Vs Ajax Web Application
Fig. Traditional Web Application
2
Fig. AJAX Web Application
Ajax incorporates:
 standards-based presentation using XHTML and CSS.
 dynamic display and interaction using the Document Object Model.
 data interchange and manipulation using XML.
 asynchronous data retrieval using XMLHttpRequest.
 and JavaScript binding everything together.
Introducing HTTP
HTTP or Hypertext Transfer Protocol is the main protocol of the World Wide Web.
Whenever you type a URL into the browser, an "http://" is prepended to the address,
indicating that you will be using HTTP to access the information at the given location.
The browser is an HTTP client, and the web page server is an HTTP server. HTTP
3
defines a set of rules regarding how messages and other data should be formatted and
exchanged between servers and browsers.
HTTP consists of two parts: a request and a response. When you type a URL in a web
browser, the browser creates and sends a request on your behalf. This request contains the
URL that you typed in as well as some information about the browser itself. The server
receives this request and sends back a response. The response contains information about
the request as well as the data located at the URL (if any). It's up to the browser to
interpret the response and display the web page.
The HTTP Request and Response
The HTTP protocol can be compared to a conversation based on a series of questions and
answers, which we refer to as HTTP requests and HTTP responses. The contents of
HTTP requests and responses are easy to read and understand, being near to plain English
in their syntax.
1. HTTP Request
The format of an HTTP request is as follows:
<request-line>
<headers>
<blank line>
[<request-body>]
After opening a connection to the intended server, the HTTP client transmits a request in
the following format:
 An opening line
 A number of header lines
 A blank line
 Optionally, a message body
The opening line is generally split into three parts; the name of the method, the path to
the required server resource, and the HTTP version being used. The request types defined
in HTTP for Ajax developers are GET and POST. Anytime you type a URL in a web
browser, the browser sends a GET request to the server for that URL, which basically
tells the server to get the resource and send it back. For example:
GET / HTTP/1.1
Host: www.wrox.com
User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.7.6)
Gecko/20050225 Firefox/1.0.1
Connection: Keep-Alive
The first part of the request line specifies this as a GET request. The second part of that
line is a forward slash (/), indicating that the request is for the root of the domain. The last
4
part of the request line specifies to use HTTP version 1.1 (the alternative is 1.0). And
where is the request sent? That's where the second line comes in.
The second line is the first header in the request, Host. The Host header indicates the
target of the request. Combining Host with the forward slash from the first line tells the
server that the request is for www.wrox.com/. (The Host header is a requirement of
HTTP 1.1; the older version 1.0 didn't require it.) The third line contains the User-Agent
header, which is accessible to both server- and client-side scripts and is the cornerstone of
most browser-detection logic. This information is defined by the browser that you are
using (in this example, Firefox 1.0.1) and is automatically sent on every request. The last
line is the Connection header, which is typically set to Keep-Alive for browser
operations. Note that there is a single blank line after this last header. Even though there
is no request body, the blank line is required.
If you were to request a page under the www.wrox.com domain, such as
http://www.wrox.com/books, the request would look like this:
GET /books/ HTTP/1.1
Host: www.wrox.com
User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.7.6)
Gecko/20050225 Firefox/1.0.1
Connection: Keep-Alive
Note that only the first line changed, and it contains only the part that comes after
www.wrox.com in the URL.
Sending parameters for a GET request requires that the extra information be appended to
the URL itself. The format looks like this:
URL ? name1=value1&name2=value2&..&nameN=valueN
This information, called a query string, is duplicated in the request line of the HTTP
request, as follows:
GET /books/?name=Professional%20Ajax HTTP/1.1
Host: www.wrox.com
User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.7.6)
Gecko/20050225 Firefox/1.0.1
Connection: Keep-Alive
Note that the text "Professional Ajax" had to be encoded, replacing the space with %20,
in order to send it as a parameter to the URL. This is called URL encoding and is used in
many parts of HTTP. (JavaScript has built-in functions to handle URL encoding and
decoding; these are discussed later in the chapter). The name-value pairs are separated
with an ampersand. Most server-side technologies will decode the request body
automatically and provide access to these values in some sort of logical manner. Of
course, it is up to the server to decide what to do with this data.
5
The POST request, on the other hand, provides additional information to the server in the
request body. Typically, when you fill out an online form and submit it, that data is being
sent through a POST request.
Here's what a typical POST request looks like:
POST / HTTP/1.1
Host: www.wrox.com
User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.7.6)
Gecko/20050225 Firefox/1.0.1
Content-Type: application/x-www-form-urlencoded
Content-Length: 40
Connection: Keep-Alive
name=Professional%20Ajax&publisher=Wiley
You should note a few differences between a POST request and a GET request. First, the
request line begins with POST instead of GET, indicating the type of request. You'll
notice that the Host and User-Agent headers are still there, along with two new ones. The
Content-Type header indicates how the request body is encoded. Browsers always encode
post data as application/x-www-form-urlencoded, which is the MIME type for simple
URL encoding. The Content-Length header indicates the byte length of the request body.
After the Connection header and the blank line is the request body. As with most browser
POST requests, this is made up of simple name-value pairs, where name is Professional
Ajax and publisher is Wiley. You may recognize that this format is the same as that of
query string parameters on URLs.
As mentioned previously, there are other HTTP request types, but they follow the same
basic format as GET and POST. The next step is to take a look at what the server sends
back in response to an HTTP request.
2. HTTP Response.
The format of an HTTP response, which is very similar to that of a request, is as follows:
<status-line>
<headers>
<blank line>
[<response-body>]
As you can see, the only real difference in a response is that the first line contains status
information instead of request information. The status line tells you about the requested
resource by providing a status code. Here's a sample HTTP response:
HTTP/1.1 200 OK
Date: Sat, 31 Dec 2005 23:59:59 GMT
6
Content-Type: text/html;charset=ISO-8859-1
Content-Length: 122
<html>
<head>
<title>Wrox Homepage</title>
</head>
<body>
<!-- body goes here -->
</body>
</html>
In this example, the status line gives an HTTP status code of 200 and a message of OK.
The status line always contains the status code and the corresponding short message so
that there isn't any confusion. The most common status codes are:





200 (OK): The resource was found and all is well.
304 (NOT MODIFIED): The resource has not been modified since the last
request. This is used most often for browser cache mechanisms.
401 (UNAUTHORIZED): The client is not authorized to access the resource.
Often, this will cause the browser to ask for a user name and password to log in to
the server.
403 (FORBIDDEN): The client failed to gain authorization. This typically
happens if you fail to log in with a correct user name and password after a 401.
404 (NOT FOUND): The resource does not exist at the given location.
Following the status line are some headers. Typically, the server will return a Date header
indicating the date and time that the response was generated. (Servers typically also
return some information about themselves, although this is not required.) The next two
headers should look familiar as well, as they are the same Content-Type and ContentLength headers used in POST requests. In this case, the Content-Type header specifies
the MIME type for HTML (text/html) with an encoding of ISO-8859-1 (which is
standard for the United States English resources). The body of the response simply
contains the HTML source of the requested resource (although it could also contain plain
text or binary data for other types of resources). It is this data that the browser displays to
the user.
Note that there is no indication as to the type of request that asked for this response;
however, this is of no consequence to the server. It is up to the client to know what type
of data should be sent back for each type of request and to decide how that data should be
used.
XMLHTTPRequest Object
This object allows for asynchronous GETs + POSTs to the server. It does not show the
user anything i.e. no status messages. We can have multiple XMLHTTPRequest active at
7
a time. It allows you to specify a handler method for state changes. Handler notified
when request is: initialized, started, in the process of being returned, completely finished
Creating XMLHTTPRequest Object
You cannot make use of the XMLHTTPRequest until you have created an instance of it.
Microsoft first introduced the XMLHTTPRequest object, implementing it in Internet
Explorer 5 as an ActiveX object. Microsoft first introduced the XMLHTTPRequest
object, implementing it in Internet Explorer 5 as an ActiveX object.
The following line creates an XMLHTTPRequest object called request:
var request = new XMLHTTPRequest();
Here we have declared a variable request and assigned to it the value returned from the
statement new XMLHTTPRequest(), which is invoking the constructor method for the
XMLHTTPRequest object.
To achieve the equivalent result in Microsoft Internet Explorer, you need to create an
ActiveX object. Here's an example:
var request = new ActiveXObject("Microsoft.XMLHTTP");
This assigns the name request to the new object.
Some versions of Internet Explorer have a different version of MSXML, the Microsoft
XML parser, installed; in those cases you need to use the following instruction:
var request = new ActiveXObject("Msxml2.XMLHTTP");
For cross Browser detection , this is the following code:
function getXMLHTTPRequest()
{
var request = false;
try
{
request = new XMLHttpRequest(); /* e.g. Firefox */
}
catch(err1)
{
try
{
request = new
ActiveXObject("Msxml2.XMLHTTP");
/* some versions IE */
}
8
catch(err2)
{
try
{
request = new
ActiveXObject("Microsoft.XMLHTTP");
/* some versions IE */
}
catch(err3)
{
request = false;
}
}
}
return request;
}
Methods and Properties of XMLHTTPRequest Object
Properties
Description
onreadystatechange Determines which event handler will be called when the object's
readyState property changes
readyState
Integer reporting the status of the request:
0 = uninitialized
1 = loading
2 = loaded
3 = interactive
4 = completed
responseText
Data returned by the server in text string form
responseXML
Data returned by the server expressed as a document object
status
HTTP status code returned by server
statusText
HTTP reason phrase returned by server
Methods
abort()
Description
Stops the current request
getAllResponseHeaders() Returns all headers as a string
getresponseHeader(x)
Returns the value of header x as a string
open('method','URL','a')
specifies the HTTP method (for example, GET or POST), the
target URL, and whether the request should be handled
9
Methods
Description
asynchronously (If yes, a='TRue'the default; if no, a='false'.)
send(content)
Sends the request, optionally with POST data
setRequestHeader('x','y')
Sets a parameter and value pair x=y and assigns it to the
header to be sent with the request
Methods:
1. open():
The open() method prepares the XMLHTTPRequest object to communicate with the
server. After you have created an XMLHttp object, you are ready to start making HTTP
requests from JavaScript. The first step is to call the open() method, which initializes the
object. The syntax is as under:
open(“method”, “URL”, [async, username, password])
You need to supply at least the two mandatory arguments to this method. First, specify
which HTTP method you intend to use, usually GET or POST as a string value. Next, the
destination URL of the request is included as the second argument. If making a GET
request, this URL needs to be suitably encoded with any parameters and their values as
part of the URL. For security reasons, the XMLHTTPRequest object is allowed to
communicate only with URLs within its own domain. An attempt to connect to a remote
domain results in a "permission denied" error message. Optionally you may include a
third argument to the send request, a boolean value to declare whether the request is
being sent in asynchronous mode. If async is set to false, the request is sent
synchronously, and JavaScript waits for a response from the server before continuing
code execution. That means if the response takes a long time, the user cannot interact
with the browser until the response has completed. The default value is true. When set to
true, the request is sent asynchronously, and JavaScript code execution continues without
waiting for the response; you must use an event handler to watch for the response to the
request.
2. send():
After creating XMLHTTPRequest using the open() method, you can send the request
using the send() method. One argument is accepted by the send() function. The syntax is
as under:
send(content)
If your request is a GET request, the request information will be encoded into the
destination URL, and you can then simply invoke the send() method using the argument
null:
10
objectname.send(null);
If your request is POST request, the content of the request (suitably encoded) will be
passed as the argument.
objectname.setRequestHeader('Content-Type', 'application/x-www-formurlencoded');
objectname.send(var1=value1&var2=value2);
In this case we use the setRequestHeader() method to indicate what type of content we
are including.
Properties:
1. onreadystate:
This property lets the user to handle asynchronous loading operations. If you assign the
name of a JavaScript function in your script to this property, that function will be called
each time the XMLHttpRequest object’s status changes - as when it’s downloading data.
You can use a shortcut to assign a Javascript function to the onreadystate change property
- you can create a function on the fly (sometimes called an anonymous function because
it doesn’t have a name). To create a function on the fly, just use the function statement
and define the body of this new function in curly braces this way:
<script language = “javascript”>
.------------function getData(dataSource, divID)
{
if(XMLHttpRequestObject)
{
var obj = document.getElementById(divID);
XMLHttpRequestObject.open(“GET”, dataSource);
XMLHttpRequestObject.onreadystatechange = function()
{
.------------}
}
}
</script>
This new, anonymous function will be called when the XMLHttpRequest object
undergoes some change, as when it downloads data. You need to watch two properties of
this object here - the readyState property and the status property.
11
2. readystate:
The readyState property tells you how the data loading is going. This property is
monitored by the onreadystatechange property, and changes in the value of readyState
cause onreadystatechange to become true and therefore cause the appropriate function to
be executed. The function called on completion of the server request is normally referred
to as the callback function. There are five possible values for readyState:





0 (Uninitialized): The object has been created but the open() method hasn't been
called.
1 (Loading): The open() method has been called but the request hasn't been sent.
2 (Loaded): The request has been sent.
3 (Interactive). A partial response has been received.
4 (Complete): All data has been received and the connection has been closed.
When a server request is first made, the value of readyState is set to zero, meaning
uninitialized. As the server request progresses, data begins to be loaded by the server into
the XMLHTTPRequest object, and the value of the readyState property changes
accordingly, moving to 1 and then 2. An object readyState value of 3, interactive,
indicates that the object is sufficiently progressed so that certain interactivity with it is
possible, though the process is not yet fully complete. When the server request has
completed fully and the object is available for further processing, the value of readyState
changes finally to 4. In most practical cases, you should look for the readyState property
to achieve a value of 4, at which point you can be assured that the server has finished its
task and the XMLHTTPRequest object is ready for use.
3. status:
The status property holds the status of the download itself. (This is the standard HTTP
status code that the browser got for the URL you supplied.) Here are some of the possible
values the status property can hold (note that a value of 200 means everything is just
fine):
 200 - OK - The request succeeded.
 204 - No Content - The document contains no data.
 401 - Unauthorized - The request needs user authentication.
 403 - Forbidden - The server has refused to fulfill the request
 404 - Not Found - The requested resource does not exist on the server.
 408 - Request Timeout - The client failed to send a request in the time allowed by
the server.
 500 - Internal Server Error - Due to a malfunctioning script, server configuration
error or similar.
12
For example:
<script language = “javascript”>
-------function getData(dataSource, divID)
{
if(XMLHttpRequestObject)
{
var obj = document.getElementById(divID);
XMLHttpRequestObject.open(“GET”, dataSource);
XMLHttpRequestObject.onreadystatechange = function()
{
if (XMLHttpRequestObject.readyState == 4 &&
XMLHttpRequestObject.status == 200)
{
-------}
}
}
}
</script>
4. statusText:
This property contains the text description of the status (such as "OK" or "Not Found").
For example:
if (xmlHttp.status == 200)
alert("Data returned is: "+ xmlHttp.responseText;
else
alert("An error occurred: "+ xmlHttp.statusText;
5. responseText and responseXML:
These properties represent the data returned from the server. To get the data from server
use either of the two properties.
The responseText property tries to represent the information returned by the server as a
text string. For example:
<script language = “javascript”>
------------function getData(dataSource, divID)
{
if(XMLHttpRequestObject)
13
{
var obj = document.getElementById(divID);
XMLHttpRequestObject.open(“GET”, dataSource);
XMLHttpRequestObject.onreadystatechange = function()
{
if (XMLHttpRequestObject.readyState == 4 &&
XMLHttpRequestObject.status == 200)
{
obj.innerHTML =
XMLHttpRequestObject.responseText;
}
}
}
}
</script>
14