CHAMPTUTORIAL

CHAMPION KAY TUTORIAL

ajax - creating an html form

Before we can start getting to the exciting new stuff, we must first make a standard HTML form (no submit button though!). This form will be spiced up in later with a hint of Ajax, but for now let's just make a solid, basic HTML form with a couple inputs.


Ajax? do you have the time:





To keep this Ajax easy to understand, we are going to be creating an HTML form that has two text fields: name and time. The name field will be filled in by the user, while the time field will be filled in using Ajax.
Below is the HTML code for your "order.html" webpage. If you would like to refresh your knowledge of forms, then check out our HTML forms lesson.

order.html HTML Code:

<html>
<body>

<form name='myForm'>
Name: <input type='text' name='username' /> <br />
Time: <input type='text' name='time' />
</form>

</body>
</html>
Save this file as "order.html"

Where?  the  submit  button?

That's the great thing about Ajax, you do not need a form submit button to send the user's data to the server. We are going to be using our "Javascript on Steroids" to get and submit data with the server.
Now that we have our HTML form, we can dive deeper into the Ajax jungle and try to discover what we're facing.

This lesson includes one of the largest hurdles for aspiring Ajax programmers:browser support. It would be nice if all the web browsers required the same Javascript code to use Ajax, but life isn't fair and you've got your work cut out for you!

This lesson will show you how to create the keystone of Ajax; the XMLHttpRequest object. Not only will you know how to make this important Ajax object, but you will also know how to make it compatible with all the popular browsers: Internet Explorer, Opera, Firefox, and Safari.

Ajax try/catch blocks of code?

To create this important Ajax object, you are going to have to use a special programming technique known as "try and catch". Basically it attempts to "try" a piece of code and if that piece causes an error it "catches" the error and keeps going. Normally when an error occurs the code will stop running, however, the "catch" eats up the error and lets the code continue.
In the following code we are going to "try" three different ways to make a new XMLHttpRequest object. Every time we fail and get an error, we will catch the error and try the next a different command.
Note: If our "try" is successful then the "catch" code will not be run because it is only used when there is an error.

order.html Javacsript Code:

<html>
<body>

<script language="javascript" type="text/javascript">
<!-- 
//Browser Support Code
function ajaxFunction(){
 var ajaxRequest;  // The variable that makes Ajax possible!
 
 try{
  // Opera 8.0+, Firefox, Safari
  ajaxRequest = new XMLHttpRequest();
 } catch (e){
  // Internet Explorer Browsers
  try{
   ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
  } catch (e) {
   try{
    ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
   } catch (e){
    // Something went wrong
    alert("Your browser broke!");
    return false;
   }
  }
 }
}
//-->
</script>



<form name='myForm'>
Name: <input type='text' name='username' /> <br />
Time: <input type='text' name='time' />
</form>
</body>
</html>
In the above Javascript code, we try three times to make our XMLHttpRequest object. Our first attempt:
  • ajaxRequest = new XMLHttpRequest();
is for the Opera 8.0+, Firefox and Safari browsers. If that fails we try two more times to make the correct object for an Internet Explorer browser with:
  • ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
  • ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");>
If that doesn't work, then they are using a very outdated browser that doesn't support XMLHttpRequest, which also means it doesn't support Ajax.
Most likely though, our variable ajaxRequest will now be set to whateverXMLHttpRequest standard the browser uses and we can start sending data to the server.




Although Adode Flash has improved performance-wise (arguably) recently and more people are upgrading to more powerful systems (desktops, laptops, notebooks, netbooks, tablets and other mobile web hardware) – still flash cannot offer what the world has been looking for. That is – even better performance cross-platform, more openness and better security (to name a just a few). Obviously the blanket ban flash has been given from some Apple products (think Iphone/Ipad) is not helping.
For the past couple of years, web technology has exploded in terms of what can be achieved using JavaScript. Things have also moved forward with HTML and CSS. The terms used to describe these recent improvements are HTML5.
Apple has mentioned many times that flash is not needed and that “everything that can be done in Flash, can be done using HTML5” (that is – HTML, JavaScript, CSS and perhaps Canvas). They are not the first to say this (Apple usually pick-up on what other already know!).
With the Iphone and Ipad selling like hotcakes, web application providers previously using Flash (or considering using it) need to have a serious think about the user reach. They could do the old-fashion thing – build a Flash web application and an alternative HTML 4 one. Or they could build one in HTML 5. Now that’s a hard one!
There are various JavaScript libraries out there with some great UI. But one of the newest ones using the very latest technologies comes from the team that brought us EXT JS (now run by Sencha). It’s called Sencha Animator. Is Sencha Animator a serious flash alternative?
Sencha Animator comes as a desktop application used to create rich HTML5 animation. It’s currently in its infancy but could have real potential. There is one drawback at this point-in-time however; it requires a Webkit browser to work. This means it will work in Google Chrome, Apple Safari, Iphone, Ipad, Blackberry torch, Google Android and other Webkit based browsers. But it will not fully work in IE, Opera or Firefox. At least not until the CSS3 is fully supported (IE 9 claims support).
At this time, many of the CSS3 techniques used by Sencha Animator are Webkit only (i.e. it has things like: -webkit-text-fill-color and -webkit-transform).
Sooner or later all major browsers should support these… but just not yet.

Basic Ajax usage with jQuery


in this article we will be talking about the basic usage of Ajax with jQuery 1.4.2 production (24KB, Minified and Gzipped).
In order to use the JavaScript examples in this article, you should first download jQuery and include it on your page using:
  1. <script type="text/javascript" src="jquery-1.4.2.js"></script>  
Throughout this article our Ajax scripts will communicate with ‘serverscript.php‘ our Server script.
  1. <?php  
  2. if(isset($_POST['firstname']) &&  
  3.    isset($_POST['lastname'])) {  
  4.  echo "Hey {$_POST['firstname']} {$_POST['lastname']}, 
  5.    you rock!\n(repsonse to your POST request)";  
  6. }  
  7. if(isset($_GET['firstname']) &&  
  8.    isset($_GET['lastname'])) {  
  9.  echo "Hey {$_GET['firstname']} {$_GET['lastname']}, 
  10.    you rock!\(response to your GET request)";  
  11. }  
  12. ?>  
Method One – POST (Asynchronous with data):
Transfer data to the server (using POST method), and retrieve a response:
  1. function doAjaxPost() {  
  2.  $.ajax({  
  3.    type: "POST",  
  4.    url: "serverscript.php",  
  5.    data: "firstname=clint&lastname=eastwood",  
  6.    success: function(resp){  
  7.      // we have the response  
  8.      alert("Server said:\n '" + resp + "'");  
  9.    },  
  10.    error: function(e){  
  11.      alert('Error: ' + e);  
  12.    }  
  13.  });  
  14. }  
  15.   
  16. doAjaxPost();  
Method Two – GET (Asynchronous with data):
Transfer data to the server (using GET method), and retreive a response:
  1. function doAjaxGet() {  
  2.  $.ajax({  
  3.    type: "GET",  
  4.    url: "serverscript.php",  
  5.    data: "firstname=clint&lastname=eastwood",  
  6.    success: function(resp){  
  7.      // we have the response  
  8.      alert("Server said:\n '" + resp + "'");  
  9.    },  
  10.    error: function(e){  
  11.      alert('Error: ' + e);  
  12.    }  
  13.  });  
  14. }  
  15.   
  16. doAjaxGet();  
Note that GET is the default type for Ajax calls using jQuery, so we really do not need to explicitly state it, but I’ve placed it there just for clarity.
Practical jQuery Example using POST:
  1. <html>  
  2. <head>  
  3.   
  4. <script type="text/javascript" src="jquery-1.4.2.js"></script>  
  5. </head>  
  6. <body>  
  7.   <script>  
  8. function doAjaxPost() {  
  9.  // get the form values  
  10.  var field_a = $('#field_a').val();  
  11.  var field_b = $('#field_b').val();  
  12.   
  13.  $.ajax({  
  14.    type: "POST",  
  15.    url: "serverscript.php",  
  16.    data: "firstname="+field_a+"&lastname="+field_b,  
  17.    success: function(resp){  
  18.      // we have the response  
  19.      alert("Server said:\n '" + resp + "'");  
  20.    },  
  21.    error: function(e){  
  22.      alert('Error: ' + e);  
  23.    }  
  24.  });  
  25. }  
  26. </script>  
  27.   
  28. First Name:  
  29. <input type="text" id="field_a" value="Sergio">  
  30. Last Name:  
  31. <input type="text" id="field_b" value="Leone">  
  32. <input type="button" value="Ajax Request" onClick="doAjaxPost()">  
  33.   
  34. </body>  
  35. </html>  

There may come a time when you wish to use other frameworks on your pages, while still using jQuery. For instance, a lot of third party JavaScript packages out there depends on one of the popular JavaScript frameworks, like ExtJS, MooTools and so on. Some of them uses the $ character as a shortcut, just like jQuery does, and suddenly you have two different frameworks trying to claim the same identifier, which might make your external scripts stop working. Fortunately the jQuery developers have already thought about situations like this and implemented the noConflict() method.

The noConflict() method simply releases the hold on the $ shortcut identifier, so that other scripts can use it. You can of course still use jQuery, simply by writing the full name instead of the shortcut. Here's a small example of it:

<div id="divTestArea1"></div>
<script type="text/javascript">
$.noConflict();
jQuery("#divTestArea1").text("jQuery is still here!");
</script>
If you think that "jQuery" is too much to type each time, you can create your own shortcut very easily. The noConflict() method returns a reference to jQuery, that you can save in your own little variable, for later use. Here's how it looks:
<div id="divTestArea2"></div>
<script type="text/javascript">
var jQ = $.noConflict();
jQ("#divTestArea2").text("jQuery is still here!");
</script>
If you have a block of jQuery code which uses the $ shortcut and you don't feel like changing it all, you can use the following construct. It's yet another version of the ready method, where $ is passed in as a parameter. This allows you to access jQuery using $, but only inside of this function - outside of it, other frameworks will have access to $ and you will have to use "jQuery":
<div id="divTestArea3"></div>
<script type="text/javascript">
$.noConflict();
jQuery(document).ready(function($) 
{
	$("#divTestArea3").text("jQuery is still here!");
});
</script>

Working with widths and heights

jQuery makes it easy for you to work with the dimensions of your elements and even the browser window. You can use the width() and height() methods for finding the dimensions, or alternatively the innerWidth()/innerHeight()/outerWidth()/outerHeight() methods, depending on the measurements you need. First a little example illustrating the differences and the some explanation:
<a href="javascript:void(0);" onclick="ShowElementDimensions();">Show element dimensions</a>
<div id="divTestArea1" style="height: 100px; width: 400px; padding: 20px; margin: 3px; border: 1px solid silver; background-color: #eee;"></div>

<script type="text/javascript">
function ShowElementDimensions()
{
	var result = "";
	
	result += "Dimensions of div: " + $("#divTestArea1").width() + "x" + $("#divTestArea1").height() + "</br>";
	result += "Inner dimensions of div: " + $("#divTestArea1").innerWidth() + "x" + $("#divTestArea1").innerHeight() + "</br>";	
	result += "Outer dimensions of div: " + $("#divTestArea1").outerWidth() + "x" + $("#divTestArea1").outerHeight() + "</br>";	
	result += "Outer dimensions of div (with margin): " + $("#divTestArea1").outerWidth(true) + "x" + $("#divTestArea1").outerHeight(true) + "</br>";	
	
	$("#divTestArea1").html(result);
}
</script>
The example is quite simple. We have a div element with extra padding, extra margin and a border. When we click the link, we use the width()/height(), innerWidth()/innerHeight() and outerWidth()/outerHeight() methods to show the dimensions of the element.

The width() and height() is simply the computed size of the element. If you use innerWidth() and innerHeight(), padding is included in the returned values. If you use the outerWidth() and outerHeight() methods, both padding and border is included in the returned values. These last methods take an optional boolean parameter which tells jQuery whether or not to include the margin as well, as you can see from the example.

The width() and height() methods can also be used to get the current dimensions of the browser window:
<a href="javascript:void(0);" onclick="ShowBrowserDimensions();">Show browser dimensions</a>

<script type="text/javascript">
function ShowBrowserDimensions()
{
	alert("Dimensions of document: " + $(document).width() + "x" + $(document).height());
	alert("Dimensions of window: " + $(window).width() + "x" + $(window).height());
}
</script>
We check the width and height for both the document (the HTML document) and the window (the browser viewport), since these may or may not differ.

Both the width() and the height() methods can also be used to set new dimensions for an element, simply by providing a parameter with the new value. Check out this example:
<a href="javascript:void(0);" onclick="ResizeElement();">Resize element</a>
<div id="divTestArea3" style="height: 100px; width: 300px; padding: 20px; border: 1px solid silver; background-color: #eee;">

<script type="text/javascript">
function ResizeElement()
{
	$("#divTestArea3").width(150).height(50);
}
</script>

Aborting an AJAX request

There may be situations where you need to cancel a running AJAX request before it ends. It's usually in cases where the user might perform an action, which sets of an AJAX request, several times within a short time period. A good example of this is auto-complete functionality for a search box, where you might try to help the user by finding related search terms based on their current input, by making an AJAX request each time they press a key in the search field. In that case, it's very likely that the user types faster than your AJAX request can be performed and therefore you would want to abort any non-finished requests, before starting the next one. Consider the following example:
<input type="button" name="btnDoRequest" value="Start" onclick="PerformSimpleCalculation();" />
<script type="text/javascript">
function PerformSimpleCalculation()
{
	$.get("/tests/calc.php", function(data, textStatus)
	{
		alert(data);
	});
}
</script>
It requests a PHP script which is doing a very complicated calculation (as you will see from the result), which means that it usually takes ~3 seconds to finish. Now, try the example and push the button several times after each other. The same "calculation" will be performed multiple times and the result will also be displayed multiple times (with a 3 second delay).

Fortunately, a call to the get() method and pretty much any other jQuery AJAX method, returns an object which, among others, contains an abort() method. We can save this reference and then call the abort() method on it if needed. Have a look at this slightly modified example:
<input type="button" name="btnDoRequest" value="Start" onclick="PerformAbortableCalculation();" />
<script type="text/javascript">
var calculationRequest = null;

function PerformAbortableCalculation()
{
	if(calculationRequest != null)
		calculationRequest.abort();
	calculationRequest = $.get("/tests/calc.php", function(data, textStatus)
	{
		alert(data);
	});
}
</script>
We start off by defining a common variable for containing the request reference. In the PerformAbortableCalculation() method, we assign the return value of the get() call to this variable, but before we do so, we check to see if it's null (the method hasn't been used yet) and if not, we call the abort() method on it. If you try this example and click several times, you will see that no matter how many times you click the button, it only executes the callback function once. 

Showing progress

When doing AJAX requests, you may want to show some sort of progress while waiting for the request to finish, especially if it might take a while for it to do so. It's actually very simple to do so with jQuery, as you will see from the following example:
<input type="button" name="btnDoRequest" value="Perform calculation" onclick="PerformCalculation(this);" />
<script type="text/javascript">
function PerformCalculation(sender)
{
	$(sender).val("Working - please wait...");
	$.get("/tests/calc.php", function(data, textStatus)
	{
		$(sender).val("Perform calculation");
		alert(data);
	});
}
</script>
Right before performing the AJAX request, we change the text of the sender (the button which calls the function). As soon as it succeeds, we set it back. That's the simplest form of progress. Another approach is to show a piece of text somewhere on the page, but the most common way of doing it is to show a little piece of graphic which illustrates that the browser is currently working. You could make one yourself, or even better: Use one of the great online generators, for instance http://ajaxload.info/. I've created one, as you can see in the next example:
<input type="button" name="btnDoRequest" value="Perform calculation" onclick="PerformCalculationWithImageProgress();" />
<img src="/images/ajax-loader.gif" style="display: none;" id="imgProgress" />
<script type="text/javascript">
function PerformCalculationWithImageProgress()
{
	$("#imgProgress").show();
	$.get("/tests/calc.php", function(data, textStatus)
	{
		$("#imgProgress").hide();
		alert(data);
	});
}
</script>
The process is pretty much the same, but instead of setting a text, we show and hide an existing image. You can place the image in a spot that the user is most likely to notice or dynamically place the image next to button/link clicked, if you have more than one. The possibilities are really endless.

There is one problem with the above examples though: If the request fails for some reason, the progress is shown but never removed again. We can fix this by subscribing to the error event, where we can then remove the progress and then show an error message. Check out this example:
<input type="button" name="btnDoRequest" value="Perform calculation" onclick="PerformCalculationWithErrorHandling(this);" />
<script type="text/javascript">
function PerformCalculationWithErrorHandling(sender)
{
	$(sender).val("Working - please wait...");
	$.get("/tests/non-existing.php", function(data, textStatus)
	{
		$(sender).val("Perform calculation");
		alert(data);
	}).error(function()
	{
		$(sender).val("Try again");
		alert("An error occurred.")
	});
}
</script>
It's pretty much identical to the first example, but here we call the error function on the returned AJAX object and pass in a callback function which should be called if the request fails, which it will in this example, since I have changed the path for the requested file to something which doesn't exist. 

In the previous chapter, we discussed the Same Origin Policy, which prevents us from making AJAX requests to a different domain or subdomain than the one currently executing the script. JSONP is a good solution to this, and in this article we will look into it.

In the following examples, we will be making calls to a PHP script on this server, but on a different subdomain. It will output an array of two users in the JSON format and the output will be JSONP compatible because the data will be surrounded by the parameter passed to the script and a set of regular parentheses. The PHP code looks like this:

<?php
$users = array
(
 array("name" => "John Doe", "age" => 42),
 array("name" => "Jane Doe", "age" => 39)
);
echo $_REQUEST['callback'] . "(" . json_encode($users) . ")";
?>
To see what data returned looks like, try opening the following URL in your browser:

http://tests.jquery-tutorial.net/json.php?callback=test

The result will look like this:

test([{"name":"John Doe","age":42},{"name":"Jane Doe","age":39}])

If you set the callback parameter to something else, you will see that change reflected in the output. This special notation is what separates regular JSON and JSONP. Now when JSON data is returned to jQuery, it parses it into objects that you may then access and use like any other JavaScript object. For instance, the above output would result in two objects, each with a name and an age property.

Now let's try requesting the page from jQuery and use the returned data. When you test this example, notice that we call the page on a different subdomain (tests.jquery-tutorial.net) than the currently executing domain (www.jquery-tutorial.net):
<ul id="ulUsers"></ul>
<script type="text/javascript">
$(function()
{
    $.get
 (
  "http://tests.jquery-tutorial.net/json.php?callback=?", 
  function(data, textStatus)
        {
         $.each(data, function(index, user)
   {
    $("#ulUsers").append($("<li></li>").text(user.name + " is " + user.age + " years old"));
   });
        },
  "json"
 );  
});
</script>
If you read the chapter on the get() and post() methods, you will see that there are only two main differences: The callback parameter on the URL, and the extra parameter specifying that we want the return type to be "json". The callback is set to a question mark, which will make jQuery generate a random one for us. In the script that takes the call, the value of this parameter is used, as you can see in the PHP code above.

Once we get some data back, we throw it into the each() method, which will loop over the data, each time invoking an anonymous method where we access the current set of data in the "user" variable. We then use the name and age of the user to construct a text representation, which we append to a list (ul tag) as a list item (li tag). As a result, we get an HTML list of the users returned by the script. 

Same Origin Policy

Same Origin Policy is a security feature found in the JavaScript implementation in most browsers, as well as in other technologies used in a browser, e.g. Flash. It basically allows you to make requests to pages within the same site/domain, while preventing you from making requests to pages on a different domain, another subdomain or through a different protocol. Since this is a part of JavaScript, it's also a part of jQuery, as you will see if you try to do an AJAX call to a page on another domain - it's simply not possible. There are certain hacks and workarounds to circumvent Same Origin Policy, but they usually don't work in all browsers or have other problems.

However, sometimes you really do need to make requests to a page on a different domain, especially in cases where you own both domains or when the owner of the secondary domain would like for you to access the page. Fortunately, the JSONP standard allows us to do just this, and while it's also a bit of a hack that would require quite a bit of effort to use within JavaScript, jQuery supports this very elegantly, allowing you to do JSONP based calls just as easy as a regular AJAX call. In fact, you can change the get() or post() call to be JSONP based simply by stating that you would like the return type to be "json".

JSON, short for JavaScript Object Notation, is a data notation, a bit like XML, allowing you to transfer structured data easily, usually over a network connection. Despite the fact that it was originally intended to use with JavaScript, a lot of other programming languages supports it out-of-the-box as well, allowing you to easily output arrays and objects in the JSON format.

The get() and post() methods

The jQuery get() and post() methods allows you to easily send a HTTP request to a page and get the result back. When you post a form, it's usually either a GET or a POST request, and with jQuery you can mimic that, since both a get() and a post() method exists.

The two methods are pretty much identical, since they simply just invoke different request types against the server. They are both static methods, which means that instead of instantiating a jQuery object and then working with that, we call get() or post() directly on the jQuery class, either by writing jQuery.get() or by using the shortcut character like this: $.get(). In its most simple form, the get() and post() methods takes a single parameter, which is the URL that you wish to request. However, in most cases you will want to do something with the returned data, in which case you can pass a callback function as a parameter, which jQuery will call if the request succeeds.

Let's do some testing. In the previous chapter, I created an HTML file called "content.html", which we loaded using the jQuery load() method. When testing the following example, make sure that you have a file called "content.html" in the same directory as the file in which you have the example. The content doesn't really matter, just write anything in there really. Here's an example of the get() method:

<script type="text/javascript">
$(function()
{
 $.get("content.html", function(data, textStatus)
 {
  alert("Done, with the following status: " + textStatus + ". Here is the response: " + data);
 });
});
</script>
The first parameter is the URL, which is just content.html. The second parameter is more interesting. It's a callback function, which jQuery calls if the page request succeeds. The first callback parameter is simply the content of the page requested, while the second callback parameter is the textual status of the request.

You can of course request a simple HTML page, like in the example above, but normally the reason for using a GET or a POST request is that you wish to pass in some parameters, which is then processed by the server, for instance with a piece of PHP, ASP or ASP.NET code, and then return the result. jQuery can take a map of GET or POST parameters, which we will try in the following example, where we use the post() method:
<script type="text/javascript">
$(function()
{
 $.post("test_post.php",
 {
  name: "John Doe",
  age: "42"
 },
 function(data, textStatus)
 {
  alert("Response from server: " + data);
 });
});
</script>
This example is much like the first one, but we make the POST request to another page, in this example a PHP page, and as the second parameter, we pass in a map of POST parameters. The map is constructed of two parameters, a name and an age. If we had used a GET request instead of a POST request (POST requests doesn't take parameters from the URL like GET does), the above code would actually have corresponded to requesting an URL like this in your browser:

test_get.php?name=John Doe&age=42

The PHP script can then read the parameters, process them and return a result. The script on our server simply takes the two values and creates a string like " is years old" and then returns it, which you can see if you test the example above. 

The load() method

As described in the previous chapter, there are many ways to use AJAX with jQuery, and they should of course be used depending on the situation. One of the simplest and yet still powerful methods for loading data asynchronously is the load() method. You use it by selecting an element where you want the content loaded to and then call the load() method on it. It takes the URL that you wish to load, as a parameter. For this example, we need a an external file that we can load. We'll call it content.html and the content of it should look something like this:
<div id="divContent">
 <b>This is external content</b>
</div>
And there's more of it
Save it as content.html, in the same directory where you keep your other example files for this tutorial. We can load it as simple as this:
<div id="divTestArea1"></div>
<script type="text/javascript">
$(function()
{
 $("#divTestArea1").load("content.html");
});
</script>
If you have the content file in another directory, or if you have named it differently, you will have to change the parameter for the load method accordingly. This is all it takes to load content from an external file with jQuery and the load method. A pretty cool trick is that you can actually pass a selector along with the URL, to only get a part of the page. In the first example, we loaded the entire file, but in the following example, we will only use the div, which contains the first sentence:
<div id="divTestArea2"></div>
<script type="text/javascript">
$(function()
{
 $("#divTestArea2").load("content.html #divContent");
});
</script>
As you can see, we simply append a standard jQuery selector to the parameter, after the URL, separated with a space. This causes jQuery to select the content out and only pass the matched part(s) back to the container. You can use any jQuery selector type to pull off this trick, which makes it pretty powerful.

The load method can take two extra parameters: A set of querystring key/value pairs, and a callback function which will be executed when the load method finishes, no matter if it succeeds or fails. Here is an example where we use the callback function to inform about the result. Normally, you would likely only show a message if the method fails, but to illustrate how it works, we do it if the method fails as well. I make sure that it fails for the example, by requesting a file which doesn't exist:
<div id="divTestArea3"></div>
<script type="text/javascript">
$(function()
{
 $("#divTestArea3").load("no-content.html", function(responseText, statusText, xhr)
 {
  if(statusText == "success")
   alert("Successfully loaded the content!");
  if(statusText == "error")
   alert("An error occurred: " + xhr.status + " - " + xhr.statusText);
 });
});
</script>
As you can see, the callback function specifies 3 parameters, which jQuery will fill in for you. The first parameter will contain the resulting content if the call succeeds. The second parameter is a string which specifies the status of the call, e.g. "success" or "error". You can use it to see if the call was successful or not. The third parameter is the XMLHttpRequest object used to perform the AJAX call. It will contain properties which you can use to see what went wrong and many other things.