Of course jQuery wouldn't be complete without a little ajax. You may have noticed that we actually use some jQuery ajax calling in the shopping cart on our sites to display various price differences between financing and paying in full on an order.
Now depending on what you plan to do with the data there are a few different calls you can use. jQuery will pass back to you either an XMLHttpRequest object, or a jQuery object. That being said the ajax calls in jQuery are similar to how you'd do them "normally". You can still set up a success method and failure method, you can serialize objects , and you are limited to same security issues that normal ajax is (no cross-domain requests). I suppose the main difference is in the initialization and how to inject the info into the DOM. For a complete overview of ajax in jQuery, checkout the ajax section in the docs at docs.jquery.com.
We're going to do a simple local xml file load as an ajax example here (mostly because ninja requested it). This may look a bit complicated, but it's not as bad as you think... seriously.
$.ajax({
url: "test.xml",
success: function(xml) {
$(xml).find('item').each(function(){
var title = $(this).find('title').text();
var url = $(this).find('link').text();
$("<li></li>").html('<a href="'+url+'">'+title+'</a>').appendTo('#div1 ul');
});
}
});
We are using an ajax method that will grab a file from the filesystem and display it. So we start the call with a "$.ajax()" call. The parameter "url" lets us specify what file to load (note that we can load almost anything through ajax, so I could have specified a js file if I'd wanted). The "success" parameter is exactly what you think it is, what should the function do if it finds the data.
Good programming standards state that you should always error handle, even if you don't think you
need to. Notice my poor example of only coding a success method in the code above, this is BAD, never,
ever, ever code without error handling! ever!
Now the world won't explode because I didn't put in a failure method (in fact the page doesn't do anything at all
if it returns null for the xml file), but it still is bad practice to not say something like "the file appears
to be missing... try again later", etc.
Next you'll notice that I am actually parsing the xml file as it is being read and saving out the parts I want into variables. Then I am creating a set of <li></li> tags and using the ".html()" method to fill them with a link and a name taken from the xml variables that I saved out. Lastly I am using the ".appendTo()" method to populate my newly constructed tags into #div1's ul.
There are a ton more things you can do with ajax, and a plethora of ways to get them done. In fact you can get over the cross-domain issue if you use JSONP, but that is something to cover another time.