Ajax
Ajax
What is Ajax?
"Asynchronous JavaScript and XML"
New name for an old technique:
JavaScript + DHTML + XMLHttpRequest
In use since at least 1997
I've used it since 2000
Finally someone gave it a name
Already enabled in your Web server and browser
Use JavaScript asynchronously behind the scenes to
load additional data (typically XML) without
discarding and reloading the entire Web page.
2
Why use Ajax?
3
Why use Ajax?
Client/Server Apps:
Dynamic data
Static forms, controls, code, etc.
Efficient, but not flexible
Traditional Web Apps:
Dynamic data
Dynamic forms, controls, code, etc.
Flexible, but inefficient, and noticeably slow
Ajax Apps:
Dynamic data
Static or dynamic forms, controls, code, etc.
Best of both worlds
4
Why use Ajax?
Geeky reasons:
Multithreaded data retrieval from Web servers
Pre-fetch data before needed
Progress indicators
Appearance of speed
Avoids need for setTimeout()
Less bandwidth required; less server load
Reload partial page, not entire page
Load data only, not even partial page
5
How much to use Ajax?
As little or as much as you like
No need to abandon what you already do
One more item in your "bag of tricks"
Start by jazzing up your existing UI
6
Ajax
Ajax stands for “Asynchronous JavaScript and XML”.
The word “asynchronous” means that the user isn’t left waiting for the server the
respond to a request, but can continue using the web page.
The “x” in Ajax stands for XML, the extensible markup language. XML looks like
HTML, which is no mistake as the latest versions of HTML are built upon XML. The
back end could send data back in XML format and the JavaScript response function
can process it using built-in functions for working with XML. The back end could
also send plain text, HTML, or even data in the JavaScript format.
We will discuss some of these methods for sending data back to the requesting
client and how it can be processed.
The XMLHttpRequest object
The XMLHttpRequest object is the backbone of every Ajax method. Each
application requires the creation of one of these objects. So how do we do it?
As with most things in web programming, this depends upon the web browser that
the client is using because of the different ways in which the object has been
implemented in the browsers.
Firefox, Safari, Opera, and some other browsers can create one of these objects
simply using the “new” keyword.
<script type="text/javascript">
ajaxRequest = new XMLHttpRequest();
</script>
The XMLHttpRequest object (cont.)
Microsoft Internet Explorer implements this object using its proprietary ActiveX
technology. This requires a different syntax for creating the object (and can also
depend upon the particular version of Internet Explorer being used).
To create one of these objects we can use a sequence of try. . . catch blocks,
attempting different ways to create an XMLHttpRequest object.
The XMLHttpRequest object (cont.)
function getXMLHttpRequest()
/* This function attempts to get an Ajax request object by trying
a few different methods for different browsers. */
{
var request, err;
try {
request = new XMLHttpRequest(); // Firefox, Safari, Opera, etc.
}
catch(err) {
try { // first attempt for Internet Explorer
request = new ActiveXObject("MSXML2.XMLHttp.6.0");
}
catch (err) {
try { // second attempt for Internet Explorer
request = new ActiveXObject("MSXML2.XMLHttp.3.0");
}
catch (err) {
request = false; // oops, can’t create one!
}
}
}
return request;
}
We list the most important of these properties and methods on the next pages.
The main idea is that the properties are set after the object is created to specify
information to be sent to the server, as well as how to handle the response received
from the server. Some properties will be updated to hold status information about
whether the request finished successfully.
The methods are used to send the request to the server, and to monitor the
progress of the request as it is executed (and to determine if it was completed
successfully).
XMLHttpRequest object properties
Property Description
We use the readyState to determine when the request has been completed, and then
check the status to see if it executed without an error. (We’ll see how to do this
shortly.)
XMLHttpRequest
Method
object methods
Description
open('method', 'URL', asyn) Specifies the HTTP method to be used (GET
or POST as a string, the target URL, and
whether or not the request should be
The open object method is used to set up the request, and the send method starts the
request by sending it to the server (with data for the server if the POST method is used).
How to use Ajax?
Simple!
Use the
XMLHttpRequest
Object
17
XMLHttpRequest Properties
onreadystatechange
Event handler (your code) that fires at each state change
readyState
0 = uninitialized 3 = interactive (some data has been returned)
1 = loading (broken in IE 6.0)
2 = loaded 4 = complete
status
HTTP Status returned from server: 200-299 = OK
responseText
String version of data returned from server
responseXML
XML DOM document of data returned
statusText
Status text returned from server
...
function myHandler() {
if (req.readyState == 4) {
doSomethingWith(req.responseXML);
}
else if (req.readyState == 3) {
showProgressIndicator();
}
}
19
Security Issues
Can only hit domain the Web page came from
Cannot access a 3rd party Web Service
However:
You can wrap those requests through your own server
User can allow access to specific sites via browser security settings
IFRAME can access any site (instead of XMLHttpRequest)
20