AJAX: A Beginning Tutorial – Part 1
It’s been a while since I’ve posted anything up here, so I figured it’s high time for something new. In this case…Ajax!
Now, Ajax has a tendency to appear intimidating to people who have never programmed anything in it, and it sure looks like that would be the case. The reality is however, that it is extremely simple to use. You don’t even really have to learn anything other than PHP (or ASP, or whatever) and Javascript. If you know how to build a webpage, you probably already know how to use Ajax.
There’s two main ways that I use Ajax, and they will be explained in Part 1 and Part 2 of this tutorial. Part 1 is going to focus on what I think should be the main use of Ajax, namely returning either a very small part of data, or returning HTML in the Ajax request itself. The second part will be focusing on returning JSON objects, and doing processing on the objects browser side.
Simple Ajax Data
One of the easiest ways to get introduced to Ajax is by returning simple data. By “simple data” I mean something like a number, or a status message, or something of the like. I happen to use this in one of the apps I created for returning a live total for an invoice. While the processing is done server side, the only thing the Ajax has to worry about is the actual number. I take the returned number, and replace a div’s content with that. And wha-la, a working ajax script. Lets take a look.
PHP
Due to myself being extremely non-creative in matters like this, we’re going to simply update a section of a webpage with the server’s date and time. So our PHP script simply needs to echo that, nothing more, nothing less.
-
<?php
-
echo date('F j Y, g:i:s A');
-
?>
Well you can’t get much simpler PHP than that
HTML
Well, now that we have a script outputting what we want, we’re going to need somewhere to put the new information. For our example a simple div will do wonders.
-
<div id="ajax_time_update"></div>
We’ll need to put the div wherever in our webpage we want the time to go of course. the only thing of interest here is that our ID must be unique, and we need to know it to reference it.
JavaScript
Javascript… This is where the magic of Ajax happens. Let me introduce the XMLHttpRequest object, your new best friend
. Actually getting a hold of the object can be kind of tricky depending on what browser the user is using, so this snippet from W3Schools is invaluable.
-
function GetXmlHttpObject()
-
{
-
if (window.XMLHttpRequest)
-
{
-
// code for IE7+, Firefox, Chrome, Opera, Safari
-
return new XMLHttpRequest();
-
}
-
if (window.ActiveXObject)
-
{
-
// code for IE6, IE5
-
return new ActiveXObject("Microsoft.XMLHTTP");
-
}
-
return null;
-
}
After you have that in your .js file (which I recommend all ajax code going into a .js… While it really doesn’t matter, it just seems cleaner to me.), the only thing left is to grab the data. We’ll call our function…UpdateDate (again, not very creative).
-
var ajaxUpdateDate;
-
-
// Initial function to kick off the update
-
function UpdateDate() {
-
// Lets get a ajax object
-
ajaxUpdateDate = GetXmlHttpObject();
-
-
// Set our URL to our PHP file
-
// Although the sid parameter doesn't do anything with the script, it stops
-
// apache from caching the result
-
var url = "http://www.thechikun.com/ajax/ajtut/part1-getdate.php?sid=" + Math.floor(Math.random()*30001);
-
-
// Set the function that will be called when the request is complete
-
ajaxUpdateDate.onreadystatechange=UpdateDateCallBack;
-
// Tell the object that we want to use the GET method, our URL, and to do it asynchronously
-
ajaxUpdateDate.open("GET", url, true);
-
// Send the request, and since we have nothing else other than the URL to send…
-
ajaxUpdateDate.send(null);
-
}
-
-
// Callback function to modify the page
-
function UpdateDateCallBack() {
-
// First, lets check if we're on ready state 4, which is done
-
if(ajaxUpdateDate.readyState == 4) {
-
// Grab the handle to the div we want to update, by the div's ID
-
var datediv = document.getElementById("ajax_time_update");
-
// Set the content of the div to be our returned value
-
datediv.innerHTML = ajaxUpdateDate.responseText;
-
}
-
}
Now, put all 3 functions (don’t forget the global varibale ajaxUpdateDate!!!) into a .js file, and include that with your HTML, like this:
-
<script type="text/javascript" src="http://www.thechikun.com/ajax/ajtut/part1-getdate.js">
-
</script>
The only thing we’re missing to call this complete is just a way to fire it off. Well thats easy enough, we’ll have a button that when you click it, calls the JavaScript function UpdateDate().
-
<input type="button" onclick="UpdateDate();" value="Check Time" />
If you’ve been following along correctly, this should be the end result.
...
Ok, so I cheated right there and used a pre instead of a div, but only cause i like the formatting
. This is pretty much it for part 1; part 2 is coming soon with JSON object manipulation.