Sie sind auf Seite 1von 20

AJAX = Asynchronous JavaScript And XML

AJAX is an acronym for Asynchronous JavaScript And XML.>

AJAX is not a new programming language, but simply a new technique for creating better,
faster, and more interactive web applications.

AJAX uses JavaScript to send and receive data between a web browser and a web server.

The AJAX technique makes web pages more responsive by exchanging data with the web
server behind the scenes, instead of reloading an entire web page each time a user makes
a change.

AJAX Is A Browser Technology

AJAX is a technology that runs in your browser. It 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.

The technology makes Internet applications smaller, faster and more user friendly.

AJAX is a web browser technology independent of web server software.

AJAX Is Based On Open Standards

AJAX is based on the following open standards:

• JavaScript
• XML
• HTML
• CSS

The open standards used in AJAX are well defined, and supported by all major browsers.
AJAX applications are browser and platform independent. (Cross-Platform, Cross-Browser
technology)

AJAX Is About Better Internet Applications

Web applications have many benefits over desktop applications, they can reach a larger
audience, they are easier to install and support, and easier to develop.

However, Internet applications are not always as "rich" and user-friendly as traditional
desktop applications.

With AJAX, Internet applications can be made richer (smaller, faster, and easier to use).

You Can Start Using AJAX Today

There is nothing new to learn.

AJAX is based on open standards. These standards have been used by most developers for
several years.

Most existing web applications can be rewritten to use AJAX technology instead of
traditional HTML forms.
AJAX Uses XML And HTTP Requests

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

The XMLHttpRequest Object

By using the XMLHttpRequest object, a web developer can update a page with
data from the server after the page has loaded!

AJAX was made popular in 2005 by Google (with Google Suggest).

Google Suggest is using the XMLHttpRequest object to create a very dynamic web
interface: When you start typing in Google's search box, a JavaScript sends the letters off
to a server and the server returns a list of suggestions.

The XMLHttpRequest object is supported in Internet Explorer 5.0+, Safari 1.2, Mozilla 1.0 /
Firefox, Opera 8+, and Netscape 7.

Your First AJAX Application

To understand how AJAX works, we will create a small AJAX application.

First, we are going to create a standard HTML form with two text fields: username and
time. The username field will be filled in by the user and the time field will be filled in using
AJAX.

The HTML file will be named "testAjax.htm", and it looks like this (notice that the HTML
form below has no submit button!):

<html>
<body>
<form name="myForm">
Name: <input type="text" name="username" />
Time: <input type="text" name="time" />
</form>
</body>
</html>
The next chapters will explain the keystones of AJAX.

AJAX - Browser Support

The keystone of AJAX is the XMLHttpRequest object.

Different browsers use different methods to create the XMLHttpRequest object.

Internet Explorer uses an ActiveXObject, while other browsers uses the built-in
JavaScript object called XMLHttpRequest.

To create this object, and deal with different browsers, we are going to use a "try and
catch" statement. You can read more about the try and catch statement in our JavaScript
tutorial.

Let's update our "testAjax.htm" file with the JavaScript that creates the XMLHttpRequest
object:

<html>
<body>
<script type="text/javascript">
function ajaxFunction()
{
var xmlHttp;
try
{
// Firefox, Opera 8.0+, Safari
xmlHttp=new XMLHttpRequest();
}
catch (e)
{
// Internet Explorer
try
{
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
try
{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e)
{
alert("Your browser does not support AJAX!");
return false;
}
}
}
}
</script>
<form name="myForm">
Name: <input type="text" name="username" />
Time: <input type="text" name="time" />
</form>
</body>
</html>

Example explained: First create a variable xmlHttp to hold the XMLHttpRequest object.
Then try to create the object with XMLHttp=new XMLHttpRequest(). This is for the Firefox,
Opera, and Safari browsers. If that fails, try xmlHttp=new
ActiveXObject("Msxml2.XMLHTTP") which is for Internet Explorer 6.0+, if that also fails, try
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP") which is for Internet Explorer 5.5+

If none of the three methods work, the user has a very outdated browser, and he or she
will get an alert stating that the browser doesn't support AJAX.

Note: The browser-specific code above is long and quite complex. However, this is the
code you can use every time you need to create an XMLHttpRequest object, so you can
just copy and paste it whenever you need it. The code above is compatible with all the
popular browsers: Internet Explorer, Opera, Firefox, and Safari.

The next chapter shows how to use the XMLHttpRequest object to communicate with the
server.

AJAX - More About the XMLHttpRequest Object

Before sending data to the server, we have to explain three important properties of the
XMLHttpRequest object.

The onreadystatechange Property

After a request to the server, we need a function that can receive the data that is returned
by the server.

The onreadystatechange property stores the function that will process the response from a
server. The following code defines an empty function and sets the onreadystatechange
property at the same time:

xmlHttp.onreadystatechange=function()
{
// We are going to write some code here
}

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

We are going to add an If statement to the onreadystatechange function to test if our


response is complete (this means that we can get our data):

xmlHttp.onreadystatechange=function()
{
if(xmlHttp.readyState==4)
{
// Get the data from the server's response
}
}

The responseText Property

The data sent back from the server can be retrieved with the responseText property.

In our code, we will set the value of our "time" input field equal to responseText:

xmlHttp.onreadystatechange=function()
{
if(xmlHttp.readyState==4)
{
document.myForm.time.value=xmlHttp.responseText;
}
}

The next chapter shows how to ask the server for some data!

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. If we assume that
the HTML and ASP file are in the same directory, the code would be:

xmlHttp.open("GET","time.asp",true);
xmlHttp.send(null);

Now we must decide when the AJAX function should be executed. We will let the function
run "behind the scenes" when the user types something in the username text field:

<form name="myForm">
Name: <input type="text"
onkeydown="ajaxFunction();" name="username" />
Time: <input type="text" name="time" />
</form>

Our updated AJAX-ready "testAjax.htm" file now looks like this:

<html>
<body>
<script type="text/javascript">
function ajaxFunction()
{
var xmlHttp;
try
{
// Firefox, Opera 8.0+, Safari
xmlHttp=new XMLHttpRequest();
}
catch (e)
{
// Internet Explorer
try
{
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
try
{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e)
{
alert("Your browser does not support AJAX!");
return false;
}
}
}
xmlHttp.onreadystatechange=function()
{
if(xmlHttp.readyState==4)
{
document.myForm.time.value=xmlHttp.responseText;
}
}
xmlHttp.open("GET","time.asp",true);
xmlHttp.send(null);
}
</script>
<form name="myForm">
Name: <input type="text"
onkeydown="ajaxFunction();" name="username" />
Time: <input type="text" name="time" />
</form>
</body>
</html>

The next chapter makes our AJAX application complete with the "time.asp" script.

AJAX - The Server-Side ASP Script

Now we are going to create the script that displays the current server time.

The responseText property (explained in the previous chapter) will store the data returned
from the server. Here we want to send back the current time. The code in "time.asp" looks
like this:

<%
response.write(time)
%>

Run Your AJAX Application

Try the AJAX application by typing some text into the Name text box below, then click
inside the Time text box:

Name: Time:

The Time text box gets the server's time from "time.asp" file without reloading the page!
AJAX Suggest Example

In the AJAX example below we will demonstrate how a web page can communicate with a
web server online as a user enters data into a standard HTML form.

Type a Name in the Box Below

First Name:

Suggestions:

Example Explained - The HTML Form

The form above has the following HTML code:

<form>
First Name:
<input type="text" id="txt1"
onkeyup="showHint(this.value)">
</form>
<p>Suggestions: <span id="txtHint"></span></p>

As you can see it is just a simple HTML form with an input field called "txt1".

An event attribute for the input field defines a function to be triggered by the onkeyup
event.

The paragraph below the form contains a span called "txtHint". The span is used as a
placeholder for data retrieved from the web server.

When the user inputs data, a function called "showHint()" is executed. The execution of
the function is triggered by the "onkeyup" event. In other words: Each time the user
moves his finger away from a keyboard key inside the input field, the function showHint is
called.

Example Explained - The showHint() Function

The showHint() function is a very simple JavaScript function placed in the <head> section
of the HTML page.

The function contains the following code:

function showHint(str)
{
if (str.length==0)
{
document.getElementById("txtHint").innerHTML="";
return;
}
xmlHttp=GetXmlHttpObject()
if (xmlHttp==null)
{
alert ("Your browser does not support AJAX!");
return;
}
var url="gethint.asp";
url=url+"?q="+str;
url=url+"&sid="+Math.random();
xmlHttp.onreadystatechange=stateChanged;
xmlHttp.open("GET",url,true);
xmlHttp.send(null);
}

The function executes every time a character is entered in the input field.

If there is some input in the text field (str.length > 0) the function executes the following:

• Defines the url (filename) to send to the server


• Adds a parameter (q) to the url with the content of the input field
• Adds a random number to prevent the server from using a cached file
• Creates an XMLHTTP object, and tells the object to execute a function called
stateChanged when a change is triggered
• Opens the XMLHTTP object with the given url.
• Sends an HTTP request to the server

If the input field is empty, the function simply clears the content of the txtHint placeholder.

The AJAX HTML Page

This is the HTML page. It contains a simple HTML form and a link to a JavaScript.

<html>
<head>
<script src="clienthint.js"></script>
</head>
<body>
<form>
First Name:
<input type="text" id="txt1"
onkeyup="showHint(this.value)">
</form>
<p>Suggestions: <span id="txtHint"></span></p>
</body>
</html>

The JavaScript code is listed below.

The AJAX JavaScript

This is the JavaScript code, stored in the file "clienthint.js":

var xmlHttp

function showHint(str)
{
if (str.length==0)
{
document.getElementById("txtHint").innerHTML="";
return;
}
xmlHttp=GetXmlHttpObject()
if (xmlHttp==null)
{
alert ("Your browser does not support AJAX!");
return;
}
var url="gethint.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("txtHint").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;
}

The AJAX Server Page - ASP and PHP

There is no such thing as an AJAX server. AJAX pages can be served by any
internet server.

The server page called by the JavaScript in the example from the previous chapter is a
simple ASP file called "gethint.asp".

Below we have listed two examples of the server page code, one written in ASP and one in
PHP.

AJAX ASP Example

The code in the "gethint.asp" page is written in VBScript for an Internet Information Server
(IIS). It just checks an array of names and returns the corresponding names to the client:

<%
dim a(30)
'Fill up array with names
a(1)="Anna"
a(2)="Brittany"
a(3)="Cinderella"
a(4)="Diana"
a(5)="Eva"
a(6)="Fiona"
a(7)="Gunda"
a(8)="Hege"
a(9)="Inga"
a(10)="Johanna"
a(11)="Kitty"
a(12)="Linda"
a(13)="Nina"
a(14)="Ophelia"
a(15)="Petunia"
a(16)="Amanda"
a(17)="Raquel"
a(18)="Cindy"
a(19)="Doris"
a(20)="Eve"
a(21)="Evita"
a(22)="Sunniva"
a(23)="Tove"
a(24)="Unni"
a(25)="Violet"
a(26)="Liza"
a(27)="Elizabeth"
a(28)="Ellen"
a(29)="Wenche"
a(30)="Vicky"
'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 30
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
'Output "no suggestion" if no hint were found
'or output the correct values
if hint="" then
response.write("no suggestion")
else
response.write(hint)
end if
%>

AJAX PHP Example

The code above rewritten in PHP.


Note: To run the entire example in PHP, remember to change the value of the url variable
in "clienthint.js" from "gethint.asp" to "gethint.php".

PHP Example
<?php
// Fill up array with names
$a[]="Anna";
$a[]="Brittany";
$a[]="Cinderella";
$a[]="Diana";
$a[]="Eva";
$a[]="Fiona";
$a[]="Gunda";
$a[]="Hege";
$a[]="Inga";
$a[]="Johanna";
$a[]="Kitty";
$a[]="Linda";
$a[]="Nina";
$a[]="Ophelia";
$a[]="Petunia";
$a[]="Amanda";
$a[]="Raquel";
$a[]="Cindy";
$a[]="Doris";
$a[]="Eve";
$a[]="Evita";
$a[]="Sunniva";
$a[]="Tove";
$a[]="Unni";
$a[]="Violet";
$a[]="Liza";
$a[]="Elizabeth";
$a[]="Ellen";
$a[]="Wenche";
$a[]="Vicky";
//get the q parameter from URL
$q=$_GET["q"];
//lookup all hints from array if length of q>0
if (strlen($q) > 0)
{
$hint="";
for($i=0; $i<count($a); $i++)
{
if (strtolower($q)==strtolower(substr($a[$i],0,strlen($q))))
{
if ($hint=="")
{
$hint=$a[$i];
}
else
{
$hint=$hint." , ".$a[$i];
}
}
}
}

// Set output to "no suggestion" if no hint were found


// or to the correct values
if ($hint == "")
{
$response="no suggestion";
}
else
{
$response=$hint;
}

//output the response


echo $response;
?>

AJAX Database Example

In the AJAX example below we will demonstrate how a web page can fetch information
from a database using AJAX technology.

Select a Name in the Box Below

Select a Customer:
Customer info will be listed here.

AJAX Example Explained

The example above contains a simple HTML form and a link to a JavaScript:

<html>
<head>
<script src="selectcustomer.js"></script>
</head>
<body>
<form>
Select a Customer:
<select name="customers" onchange="showCustomer(this.value)">
<option value="ALFKI">Alfreds Futterkiste
<option value="NORTS ">North/South
<option value="WOLZA">Wolski Zajazd
</select>
</form>
<p>
<div id="txtHint"><b>Customer info will be listed here.</b></div>
</p>
</body>
</html>

As you can see it is just a simple HTML form with a drop down box called "customers".

The paragraph below the form contains a div called "txtHint". The div is used as a
placeholder for info retrieved from the web server.

When the user selects data, a function called "showCustomer()" is executed. The execution
of the function is triggered by the "onchange" event. In other words: Each time the user
change the value in the drop down box, the function showCustomer is called.

The JavaScript code is listed below.

The AJAX JavaScript

This is the JavaScript code stored in the file "selectcustomer.js":


var xmlHttp

function showCustomer(str)
{
xmlHttp=GetXmlHttpObject();
if (xmlHttp==null)
{
alert ("Your browser does not support AJAX!");
return;
}
var url="getcustomer.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("txtHint").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;
}

The AJAX Server Page

The server page called by the JavaScript, is a simple ASP file called "getcustomer.asp".

The page is written in VBScript for an Internet Information Server (IIS). It could easily be
rewritten in PHP, or some other server language. Look at a corresponding example in PHP.

The code runs an SQL against a database and returns the result as an HTML table:

<%
sql="SELECT * FROM CUSTOMERS WHERE CUSTOMERID="
sql=sql & request.querystring("q")

set conn=Server.CreateObject("ADODB.Connection")
conn.Provider="Microsoft.Jet.OLEDB.4.0"
conn.Open(Server.Mappath("/db/northwind.mdb"))
set rs = Server.CreateObject("ADODB.recordset")
rs.Open sql, conn

response.write("<table>")
do until rs.EOF
for each x in rs.Fields
response.write("<tr><td><b>" & x.name & "</b></td>")
response.write("<td>" & x.value & "</td></tr>")
next
rs.MoveNext
loop

response.write("</table>")
%>

AJAX XML Example

In the AJAX example below we will demonstrate how a web page can fetch information
from an XML file using AJAX technology.

Select a CD in the Box Below

Select a CD:
CD info will be listed here.

AJAX Example Explained

The example above contains a simple HTML form and a link to a JavaScript:

<html>
<head>
<script src="selectcd.js"></script>
</head>
<body>
<form>
Select a CD:
<select name="cds" onchange="showCD(this.value)">
<option value="Bob Dylan">Bob Dylan</option>
<option value="Bonnie Tyler">Bonnie Tyler</option>
<option value="Dolly Parton">Dolly Parton</option>
</select>
</form>
<p>
<div id="txtHint"><b>CD info will be listed here.</b></div>
</p>
</body>
</html>

As you can see it is just a simple HTML form with a simple drop down box called "cds".

The paragraph below the form contains a div called "txtHint". The div is used as a
placeholder for info retrieved from the web server.
When the user selects data, a function called "showCD" is executed. The execution of the
function is triggered by the "onchange" event. In other words: Each time the user change
the value in the drop down box, the function showCD is called.

The JavaScript code is listed below.

The AJAX JavaScript

This is the JavaScript code stored in the file "selectcd.js":

var xmlHttp
function showCD(str)
{
xmlHttp=GetXmlHttpObject();
if (xmlHttp==null)
{
alert ("Your browser does not support AJAX!");
return;
}
var url="getcd.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("txtHint").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;
}

The AJAX Server Page

The server page called by the JavaScript, is a simple ASP file called "getcd.asp".
The page is written in VBScript for an Internet Information Server (IIS). It could easily be
rewritten in PHP, or some other server language. Look at a corresponding example in PHP.

The code runs a query against an XML file and returns the result as HTML:

<%
q=request.querystring("q")

set xmlDoc=Server.CreateObject("Microsoft.XMLDOM")
xmlDoc.async="false"
xmlDoc.load(Server.MapPath("cd_catalog.xml"))

set nodes=xmlDoc.selectNodes("CATALOG/CD[ARTIST='" & q & "']")

for each x in nodes


for each y in x.childnodes
response.write("<b>" & y.nodename & ":</b> ")
response.write(y.text)
response.write("<br />")
next
next
%>

How does AJAX work

The pursuit of a development technique like AJAX came from the need for making web
applications much more usable and eliminating their key disadvantages in comparison with
the desktop platform:

• Poor Interactivity – web applications require that users wait for full page reloads
after each interaction with the server. During the loading time they have to stare at
a blank screen, which tremendously disturbs the whole experience. Although
broadband internet connections are becoming a standard, web applications are
also becoming increasingly complex and "heavy" so the overall waiting time
remains relatively the same.
• Unresponsiveness – classic web applications transfer the complete form data to
the server, which in turn renders and sends back the full HTML markup of the page
to the browser. This happens during each postback and in most cases is highly
inefficient, since only a small part of the interface is actually changed. However,
lots of bandwidth is consumed and the performance is significantly hindered. This
leaves users with the idea that web applications are slow by nature. Even worse,
the user will often find the page has scrolled to a different position, causing
disorientation.
• Simplistic Interfaces – the requirement for full page postback whenever the user
interface has to be changed imposes hefty limitations on the degree of
sophistication of web user interfaces. Rich and smooth interfaces with on-demand
update could only be implemented using Flash technology. This approach, however,
is impractical for general use since it is very complex and requires a much different
set of skills than those possessed by the typical web developer. It can also cause
end-user issues as a plug-in is often required.
• Low Usability – if a web application reloads the whole page because the user
made a new selection on a form, they will get confused. It is often the case that
web applications work in a confusing and esoteric way because the web application
has been built around the standard, simple view of the Internet protocols. ASP.NET
meant we could build applications with more functionality more quickly, usability
has a way to go yet.

AJAX was born with the idea to change all this and narrow the functional gap between the
desktop and the web. The new generation of AJAX-enabled applications delivers close-to-
instantaneous performance, rich interfaces and tremendously improved user experience. It
opens new horizons for much closer interaction with the application and demonstrates in
practice what was until recently considered impossible:

• Real-time map panning in Google Maps and Virtual Earth is just like image panning
in Adobe® Photoshop®
• Folder browsing, message previewing, etc. in Microsoft® Outlook® Web Access is
identical to that in the desktop version of Outlook.
• Validation checking on complex input fields can be performed by the server,
without reloading the page.
• Virtual scrolling of huge tables with telerik r.a.d.grid is as fast as in Microsoft
Excel®

What's interesting to know is that AJAX is not actually that new as a technology. It has
been first used after Microsoft implemented Microsoft.XMLHTTP COM object that was part
of The Microsoft® XML Parser distributive. As an ActiveX object in Internet Explorer 5, it
was used to create the famous Outlook Web Access. You have probably seen AJAX in
action for quite long in the MSDN Documentation treeview navigation. What is new actually
is the name AJAX, which was widely accepted in 2005. Other labels for the same
technology are Load on Demand, Asynchronous Requests, Callbacks, Out-of-band Calls,
etc.

What's even more interesting is that AJAX is actually not a technology. It is more like a
development technique that utilizes in a unique way a number of already mature
technologies: HTML/XHTML, XML, DHTML, the XmlHttpRequest object, and JavaScript. For
the purposes of simplicity we will refer to it as technology as it is widely accepted as such
and provides a useful language to discuss the characteristics of the significant trend it
represents.

How does AJAX work?

The core idea behind AJAX is to make the communication with the server asynchronous, so
that data is transferred and processed in the background. As a result the user can continue
working on the other parts of the page without interruption. In an AJAX-enabled
application only the relevant page elements are updated, only when this is necessary.
In contrast, the traditional synchronous (postback-based) communication would require a
full page reload every time data has to be transferred to/from the server. This leads to the
following negative effects:

• The user interaction with the application is interrupted every time a server call is
needed, since a postback has to be made.
• The user has to wait and look at blank screen during each postback.
• The full page is being rendered and transferred to the client after each postback,
which is time consuming and traffic intensive.
• Any information entered by the user will be submitted to the server, perhaps
prematurely.

The AJAX-enabled applications, on the other hand, rely on a new asynchronous method of
communication between the client and the server. It is implemented as a JavaScript engine
that is loaded on the client during the initial page load. From there on, this engine serves
as a mediator that sends only relevant data to the server as XML and subsequently
processes server response to update the relevant page elements.

Below is a diagram of the complete lifecycle of an AJAX-enabled web form.

1. Initial request by the browser – the user requests the particular URL.
2. The complete page is rendered by the server (along with the JavaScript AJAX
engine) and sent to the client (HTML, CSS, JavaScript AJAX engine).
3. All subsequent requests to the server are initiated as function calls to the
JavaScript engine.
4. The JavaScript engine then makes an XmlHttpRequest to the server.
5. The server processes the request and sends a response in XML format to the client
(XML document). It contains the data only of the page elements that need to be
changed. In most cases this data comprises just a fraction of the total page
markup.
6. The AJAX engine processes the server response, updates the relevant page
content or performs another operation with the new data received from the server.
(HTML + CSS)

Example: The AJAX-based VirtualScrolling feature of telerik r.a.d.grid loads on demand


only the visible page of the grid, which makes possible to browse of 100,000+ records
almost in real-time.
(See live demo)

Problems and Challenges


The benefits of the AJAX development technique may look very attractive, but its practical
implementation from scratch is usually a complex task, which only advanced developers
can undertake. Among the pitfalls you will face are:

• Writing and Maintaining Complex JavaScript – building AJAX-enabled


applications requires substantial JavaScript skills, which may turn to be a problem
for a large number of .Net developers. Furthermore, the lack of good debugging
tools for client-side script makes the process even more complicated.
• ViewState Management – ASP.NET web controls properly maintain their
ViewState between postbacks. The same, however, does not apply for AJAX
callbacks. As a result, developers need to figure a way for the proper management
of the page ViewState.
• Breaking the Page Paradigm – AJAX requires a different way of thinking about a
web-site, since the concept of a "Page" is no longer valid. In fact, AJAX applications
may be considered as closer to the desktop-applications development approach.
The fact that a Page no longer holds constant data leads to two important
consequences – the Back button and bookmarking will no longer work as expected.
Therefore, developers need to implement specific mechanisms for overcoming
these two issues.
• Accessibility – the AJAX development technique fundamentally violates the
requirements for accessibility. Since the page content is being updated
dynamically, the changes may not be detected by accessibility tools like screen
readers. Furthermore, some accessibility standards prohibit the use of JavaScript
altogether, which practically eliminates the possibility for using AJAX.
• New UI Interactivity Requires Learning – the UI richness of AJAX-enabled
application presents users with new and unexpected functionality. Although this is
the main reason for using AJAX in the first place, it may require some learning.

Das könnte Ihnen auch gefallen