Вы находитесь на странице: 1из 6

29/01/2011 Ajax tutorial

This is a printer-friendly vers ion. The navigation and other unnecessary elements have been removed. Come
back and vis it us at www.yourhtmlsource.com. Enjoy!

PATH // www.yourhtmlsource.com → JavaScript → AJAX

Ajax
by Ross Shannon

When you want a user to send data to your server — once they have filled out a form, for example — they
normally have to s ubmit the form and then wait as the entire page is refreshed. Similarly, if you want to retrieve
new data from the s erver, you have no choice but to load a whole new page.

This is inefficient, time-consuming, and particularly frustrating if there’s only a small amount of data being sent
back and forth. In this tutorial, you’ll be introduced to Ajax, a technology that allows you to send these requests
through small JavaScript calls, meaning the user doesn’t have to wait for the page to refresh.

This page w as last updated on 2010-01-08

W hat is “Ajax”?

Ajax is actually a family of technologies that have been available for years. The means to make requests to the
server using only JavaScript were built into Internet Explorer 5.5, but the possibilities of the technology were
overlooked. It was only in 2005 that the techniques were rediscovered and used, notably to excellent effect in
Google’s » GMail web application.

The term Ajax, which stands for “Asynchronous JavaScript and XML”, was first coined by Jesse James Garrett in
his somewhat infamous article, » Ajax: A New Approach to Web Applications.

So let’s take each of those parts in isolation. Ajax is:

Asynchronous

yourhtmlsource.com/javascript/ajax.html 1/6
29/01/2011 Ajax tutorial
This means that when you send a request, you wait for the response to come back, but are free to do
other things while you wait. The res ponse probably won’t come back immediately, so you set up a
function that will wait for the response to be sent back by the server, and react to it once that happens .
JavaScript
JavaScript is used to make a request to the server. Once the response is returned by the server, you will
generally use s ome more JavaScript to modify the current page’s document object model in some way
to show the user that the s ubmiss ion went through successfully.
XML
The data that you receive back from the server will often be packaged up as a snippet of XML, so that it
can be easily process ed with JavaScript. This data can be anything you want, and as long as you want.

There’s nothing really new about what is happening here. We’re requesting a file (which will often be a s erver-
side script, coded in s omething like PHP), and receiving a page as the response. This is how the web works
already — the only difference is that now we can make these requests from JavaScript.

Cross-browser Ajax

Unfortunately Ajax is s upported slightly differently in IE than it is Safari, Opera and Mozilla-based browsers like
Firefox. This leaves us with two pos sible routes: using code branching to send the right code to each brows er
based on which model they s upport, or us ing a JavaScript library that wraps up the Ajax code into a single
object, and means you don’t have to worry about browser incompatibilities.

We’re going for the latter option, and will be using a JavaScript library. There are dozens of them in existence,
each with their own boons and vices. Popular examples include prototype, Dojo, and the Yahoo UI library. For
the duration of this tutorial, we’re going to be using a very useful library called » Sarissa. Sarissa contains
methods that will create the request for us , and also methods that help with processing the XML that we receive
back in the respons e. This means we don’t have to mess with the intricacies of Ajax, and allows our code to be
quite elegant.

Building a Request

So, first » download the Sarissa JavaScript source code file (called “sarissa.js”) and then upload it with the rest
of your files. You’ll need to show your pages where the library is, so add this line to the top of any pages that
need access to Ajax:

<script type="text/javascript" src="sarissa.js"></script>

First of all, the project we’re going to work on throughout this tutorial is to make form submissions for a survey
less painful. You can get a glimpse of what we’re aiming for in this example page. The user will be
presented with a set of options, be as ked to choose one, and press submit. Instead of having to reload the
whole page to s ubmit the form, which might turn some users off participating in the survey, we will instead
submit the form with Ajax, and update the page when the request succeeds.

I’ll go through the four steps required to get this working, and we’ll get onto the full code later. First we’ll begin to
construct our request. The specific method we use to do this is called “XML HTTP Request.” Through Saris sa,
we create a cros s-browser XML HTTP Request object:

yourhtmlsource.com/javascript/ajax.html 2/6
29/01/2011 Ajax tutorial

va r x m lhttp = new XMLHttpR equest();

That code there will take care of the brows er compatibility issues, and leave you with an object that will work in
whatever the user’s browser can support. Next we specify the page that we’re requesting:

x m lhttp.open('PO ST ', 'rating-submit.php', true );

The first argument to this function can be s et to either 'GET ' or 'P O ST'. In this instance, because we’re sending
some data to the s erver, we use the ‘POST’ method. If we were only pulling additional data from the server, we
could use the ‘GET’ method safely. This distinction is important to get right. Only use ‘GET’ if you are not
changing anything on the server, just retrieving some data. Otherwise you should always use ‘POST’. Keep the
names capitalised.

Obviously you will need to change that URL to the filename of the script you’re using on your own server. The
third argument controls whether the request is asynchronous or synchronous. If set to false , the call is made
synchronous and the user’s browser will actually lock up until the response is received, which is not what we
want. You will almost always leave this as true .

The next step is to set up the function that will wait to be called until a response is returned by the server. This
function is respons ible for doing something to show the user that the submission has succeeded. Usually,
adding a small mess age to the page is enough. The “callback function,” as it is called, always follows the same
structure, which looks like this:

x m lhttp.onrea dystatechange = function() {


if (xm lhttp.readySta te == 4) {
// Your callba ck code go es here
}
}

As a request is made, it pass es through various states. We check the object’s readySta te property here to see if
it has made it to stage 4, which means that the response is complete.

The last step now that this is all set up is to actually send the request:

x m lhttp.send(null);

This will send the request and then return immediately. It then waits for the response to enter readySta te 4.
When that happens, your callback function is called, and whatever data was sent back in the response (if any) is
available in the xm lhttp.respo nseXML variable. And that’s all there is to it.

Building the Script

So now that we have a skeleton for the script, we can start filling it out properly. This script will use a number of
functions from the very us eful util-functions.js file, which is a collection of functions I put together that you are
welcome to download and use in your own projects.

First, we’re going to loop through the page once it loads and add an event handler to any form with the class
“ajaxify.” The event handler will be fired when the form is submitted:

a ddEve nt(window, 'loa d', init, fa lse);

yourhtmlsource.com/javascript/ajax.html 3/6
29/01/2011 Ajax tutorial

functio n init() {
if (!Sarissa || !docum ent.getEle m e ntsByTagNam e) return;

var form Ele m ents = docum ent.ge tElem entsByT agNam e('form ');
for (var i = 0; i < form Elem ents.le ngth; i++) {
if (form Elem ents[i].classNam e.m atch(/\baja xify\b/)) {
a ddEve nt(form Ele m e nts[i], 'subm it', subm itR ating, fa lse);
}
}
}

So here we’re firs t checking if the user’s browser has correctly loaded the Sarissa object, and is also able to do
the docum ent.ge tElem entsByTa gNa m e method. If this doesn’t work out, we return early. Then we’re looping
through all the forms on the page and adding an event handler to any that have a class name that matches the
string “ajaxify.” Next we have to actually write that subm itR ating function. It looks like this:

functio n subm itRa ting(e ) {


/* Cancel the submit event, and find out which form was submitted */
kna ck erEve nt(e);
var target = window.event ? window.event.srcEle m e nt : e ? e.targe t : null;
if (!target) return;

/* Set up the request */


var xm lhttp = new XMLHttpRe que st();
xm lhttp.o pen('PO ST', 'rating-subm it.php', true);

/* The callback function */


xm lhttp.o nre adysta techa nge = function() {
if (x m lhttp.rea dyState == 4) {
if (xm lhttp.sta tus == 200)
addRatingFe edback(xm lhttp.respo nseXML, target);
e lse
target.subm it();
}
}

/* Send the POST request */


xm lhttp.se tR eque stHeader('C ontent-T ype', 'applicatio n/x-www-fo rm -urlenco ded');
xm lhttp.se nd('rating=' + target.elem ents['rating'].va lue);

}

The Callback Function

Let’s look at the callback function in a little more depth. We’ve added a new check in there.

if (xm lhttp.readyState == 4) {
if (xm lhttp.status == 200)
addR atingFeedback(xm lhttp.response XML, target);
else
ta rge t.subm it();

yourhtmlsource.com/javascript/ajax.html 4/6
29/01/2011 Ajax tutorial
}

Just because we’ve received a response back doesn’t mean that everything went according to plan. When the
response is sent back by the server, it is always sent with a status code, of which there are many. The response
code 200 (known as “Ok”) means that the response went through without a hitch, which is obviously what we
want to hear. If xm lhttp.status is set to 200, then we can go ahead and add some feedback to the page.

Otherwise, in the case of a timeout or if the script returned a 404 error, we need to have a backup plan. Here,
I’ve decided to simply submit the form normally. This illustrates an important point: even with all of this Ajax
goodness, you still need to have a s cript on the server that will deal with normal form submits from users with
browsers that don’t support Ajax, or just for those times when something goes wrong.

Sending the POST Request

Sending a POST request, as opposed to a GET request, requires an extra step. We need to set a special
attribute of the request, so that it accepts some data from the form. We then need to extract the relevant data
from the form and include this in the send() call.

x m lhttp.setRe questHe ade r('Co nte nt-Type', 'applica tion/x -www-fo rm -urlencoded');
x m lhttp.send('rating=' + ta rge t.e lem ents['rating'].value);

As you can see, we’re no longer s imply calling se nd(null). We send the data from the form in the format
“name=value&name=value...”. So here we’re working with the select called “rating”, and sending its value, which
will end up looking something like “rating=3”.

The Server-side Script

Everyone’s server-s ide script is going to be different, but for the sake of completeness, here’s what the one in
our example looks like:

<?php
header('Content-type: text/xml');

$rating = $_POST['rating'];

function record_rating($rating) {
// Add data to database here
return 1;
}
?>
<xmlresponse>
<rating><?= $rating ?></rating>
<result><?= record_rating($rating) ?></result>
</xmlresponse>

This simply sends back a small XML document. You can make up whatever tags you want. The “record_rating”
method I’ve glos sed over here will s ave some data on the server, and then return a 1 if the operation was
successful, but a 0 if the operation failed. This way you can check the contents of the <result> tag and add
feedback appropriately.

yourhtmlsource.com/javascript/ajax.html 5/6
29/01/2011 Ajax tutorial

Adding Feedback

The final step is to check the response and add feedback to the page appropriately. Again, this will be different
for everyone’s implementation. The XML that was sent back by your server-side script is available in the
xm lhttp.respo nseXML property. You can treat this just as you would a HTML document, which means that
methods calls like the one below will yield the contents of certain elements in the XML:

x m lhttp.re sponseXML.getEle m e ntsByTagNam e('re sult')[0].firstC hild.data ;

That code snippet above will return the contents of the first <result> element in the response (i.e. the value you
should check to make sure the s erver-side script executed correctly). The feedback you give the user can range
from popping up an ale rt() to rearranging the page using DOM calls. In the example page you can s ee that I
add new text to the page, restyle the form and then disable the form inputs so that the user doesn’t submit the
same form twice.

So there you have it, an Ajax-ified page from start to finish. Ajax has lots of useful applications. Have fun with it.

Like 1,803 people like this.

yourhtmlsource.com/javascript/ajax.html 6/6

Вам также может понравиться