Ajax Tutorial: Implementation
Last time I talked about the theory of ajax requests. Today I’ll start to shed light on the heart and soul of making ajax requests. The javascript. This section assumes basic knowledge of javascript. The goal isn’t to understand the background of how ajax request are done, but to know how to implement ajax techniques with modern libraries. I can’t resists starting off with a little background, so you can fully appreciate the nonsense that these programmers have to deal with.
Old-School
Everything could be so easy… if it weren’t for IE. That is a little unfair since IE got it all started, but the implementation is far from sexy. To make matters worse Firefox, Safari, and co use a different method. Here’s the deal:
An xml-http-request object is used to make an asynchronous request. There are two types, the Microsoft one is built on ActiveX and looks like this:
var xhr = new ActiveXObject("Microsoft.XMLHTTP");
The Safari, Mozilla, ... version is a normal class and instantiating it looks like this:
var xhr = new XMLHttpRequest();
That would be too easy...here are two more Microsoft ones:
var xhr = new ActiveXObject("MSXML2.XMLHTTP.3.0");
var xhr = new ActiveXObject("MSXML2.XMLHTTP");
Luckily, once the browser check is done, the objects can be treated identically. The object’s open() and send() methods can now be used to make a request, and you can specify your own function to handle the return by tying it to ‘onreadystatechange’. The Mozilla developers center has a great intro to the old-school way.
Test Environment
If there is one thing I can’t stand, it’s debugging. Having a lot of files doesn’t make that any easier, so here’s a one-file setup that I used while I was taking my first steps with ajax. In fact, I still use it for debugging today:
<?php
// 'Backend' code
if (isset($_SERVER['HTTP_X_REQUESTED_WITH'])
AND $_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest')
{
echo 'ajax request';
exit;
}
?>
<html>
<head>
<title>Ajax Test</title>
<script src="path/to/library.js" type="text/javascript"></script>
<script type="text/javascript" charset="utf-8">
// Your javascript code here
</script>
</head>
<body>
<p>Some elements <a id="link">to play around with</a></p>
</body>
</html>
So how can you use that to streamline the learning process? Easy, make all your calls to the current url. You’ll be able to edit the javascript and the response in the same file. It’s totally unspectacular and yet it has worked so well for me I feel it was worth mentioning.
JavaScript Libraries
As you know, we no longer need to worry about any of the old-school stuff (::yay::). Instead, there is a plethora of javascript libraries that are thoroughly tested and have stood the test of (at least some) time. For the purpose of this series all you need is a library that eases the ajax process: jQuery, Prototype, Mootools, Dojo, YUI are all fine and perfectly capable of this.
A quick survey of the readers of my blog (hey there, self) reveals that jQuery is the most commonly used library. While I personally prefer some of the others for their more descriptive syntax, I will use jQuery here. It’s the easiest to implement, even if I think the $ object/selector/supermodel thing is far from cool (ambiguous is what I would call it).
Always start by looking at the pertinent documentation here. Wow, that’s a lot of choices for something as simple as an ajax call, what do I use? I personally like the first. It’s the most general choice - all the others are just wrapper functions. Assuming you’re still using the setup outlined above, here is how you can get the echoed text:
$.ajax({
type: "GET",
url: "",
success: function(msg){
alert("Simon says: " + msg);
}
});
Let’s take a look line-by-line:
1) Request type, we’re not sending any data so a GET request is a good choice
2) Url, blank because we’re self submitting
3) Callback function - shows an alert of the returned content (msg holds that text)
But how did it know?
It’s a simple snippet, but what happens in the background? In the background, the script opens another browser, points it at the same url, and waits for the page to load. It then selects the whole page, copies it, goes back to your script and pastes the whole thing into the callback function parameter.
How did the backend know to echo and not show the page? That magic happens in the $_SERVER[’HTTP_X_REQUESTED_WITH’] check. Ajax requests are sent with a different header than normal pages, you can use that to your advantage and use it as an indicator of an ajax request.
Advanced Examples
This post is already longer than expected, so I’m going to hold off on advanced examples until next time. The advanced example will be a login form using the above one-file approach. Part 4 will then integrate it all with CodeIgniter.
Comments
#1 | Posted on July 20th, 2008 InterCoder said:
I didn’t know you could use $_SERVER[’HTTP_X_REQUESTED_WITH’] to indicate if the page is called by AJAX or by a person.
I’ve got to implement this in my website, because it will save me a lot of lines of code!
Thank you ^.^