jQuery Tutorial (Part 5): AJAX Them All!

programming101   jQuery Tutorial (Part 5): AJAX Them All!As we near the end of our jQuery mini-tutorial series, it’s about time we took a more in-depth look at one of the most used features of jQuery. AJAX allows a website to communicate with a server in the background without require the entire page to reload. From Facebook-style infinite status streams to submitting form data, there’s a million different real life situations in which this technique can be useful.

If you haven’t read the previous tutorials, I suggest you do so before tackling this as they build upon each other.

A-What?

AJAX is an acronym for Asynchronous Javascript and XML, but the keyword here is asynchronous. Asynchronous refers to the fact these requests occur in the background, not interrupting the browsing experience of the user. You’ve probably never even noticed it before, but if a website is updating itself dynamically, there’s a good chance it’s using AJAX to do so.

Before AJAX, any form of interaction with a server, be it fetching new data or posting information back from the user, would have to have been done using a new page load and redirections.

facebook ajax   jQuery Tutorial (Part 5): AJAX Them All!

Today we’re going to look at using a third party service, Flickr – from whom we can use AJAX to fetch some pictures using a JSON datatype. It doesn’t actually matter how Flickr implements the receiving side of things, because that’s the beauty of APIs – all we need to know is an API URL, what kind of data we’re going to get back, and how to manipulate it.

For further reading, I wrote another tutorial a while ago about handling AJAX in WordPress for a contact form submission, so you may want to check that out too; it involves writing your own PHP handler, and integrating that into the “official” WordPress AJAX process.

The AJAX Method

Here’s the basic format of an AJAX request:

$.ajax({ 
type: "GET or POST", 
url: "API or your PHP handler URL ", 
datatype:"JSON", 
// depending on what kind of data you want back, but JSON is the most common 
data: { //a set of key:"value" pairs }, 
success:function(data){ //handle a successful return of data }, 
error:function(message){ //handle the error } });

This looks fairly complex at first – not helped by the lack of indentation from this code plugin – but you’ll see how easy it is when get to a real world example.

Flickr API AJAX

In this example, we’re going to grab the tags associated with the current WordPress post, and fetch some images to append at the end of the article. There’s a similar example in the jQuery documentation, but it uses a short cut method called getJSON() rather than explaining a full AJAX format. While this is a valid way of doing things if you know you’re only going to get JSON data back, I feel that learning the actual AJAX method is more important, so that’s how we’ll do it.

First, one up single.php and we’ll try to echo out a simple comma separate list of the current post tags. Typically, you would use the_tags() to do this, but that’s no good as we want to eventually store these as a variable, whilst the_tags() echoes them straight out pre-formatted. Instead, we’ll use get_the_tags():

<?php
$tagslist = get_the_tags();
foreach($tagslist as $tag){
echo $tag->name.",";
}?>

This works nicely, so we’ll output this inside of an AJAX request to the Flickr API URL as follows (note, this is a screenshot – in order to preserve indentation, the code is available at this PasteBin).

ajax code   jQuery Tutorial (Part 5): AJAX Them All!

At this point, all it does it to output to the browser console, or alert an error message if there is one. To actually do something with the returned data, add somewhere for the images to placed:

<div id="flickr"></div>

And edit the success parameter of the AJAX call to iterate over the items that are returned.

$.each(data.items, function(i,item){
 if(i==3) return false; // stop when we have 3
 $("#flickr").append("<a href='"+item.link+"'><img style='width:33%' src='"+item.media.m+"'/></a>");
 });

And there we have it. We’re appending 3 items from the returned JSON object (the data is zero indexed, so if get to item 3, we’re actually at the fourth item. Confusing, I know. At that point, we use return false to jump out of the each() iterator). I’ve already examined the contents of the objects that are returned, so I know the data structure and I’m only extracting a link and IMG reference. If you’re interested in knowing what else is returned, just throw a console.log(item) in there.

Here’s the results on my test site, and the full code at this PasteBin. Notice that the results returned are basically junk – my post included the tag DIY for a walk-in chicken run, and Flickr has given me DIY knitting. Nice. Of course, this is one of the hurdles you face when working with an API and doing things automatically; you could either re-tag your posts (a considerable undertaking), change the request to ask for “all” tags instead of “any” (likely to return nothing in this case), or come up with a new custom field to which you would specify a targeted keyword to use with the API (probably the easiest).

flickr demo   jQuery Tutorial (Part 5): AJAX Them All!

SEO Considerations

This isn’t a major point, but since you’re in the business of developing websites it should be mentioned: search engines won’t index content that doesn’t exist at page load, such as anything done via AJAX. The absolute worst thing you could do would be to fully AJAXify your blog so that the homepage was merely an iframe-like container for all the content which is loaded in dynamically. Use AJAX wisely, to enhance the page content, not as a replacement. Or face dire consequences.

Thanks for reading, and I hope I’ve given you some ideas. Of course, Flickr isn’t the only API out there – just Google “public API” and you’re sure to find more things you could play around with.

Next week will be the final lesson in the jQuery Tutorial series as we check out the jQuery UI plugin. As ever, comments and suggestions welcome; if you have a question that others will benefit from, consider posting it to our Answers site.

The comments were closed because the article is more than 180 days old.

If you have any questions related to what's mentioned in the article or need help with any computer issue, ask it on MakeUseOf Answers—We and our community will be more than happy to help.

3 Comments -

Mitesh Budhabhatti

One of the best series of programming articles I’ve ever read. Thanks !!!

Csaba S

I just learn how to use jquery on my sites.. i am a beginner now, but i hope i will be better! This articles help a lot to me :)

Jay Kanakiya

There are dozens of jquery plugins that help in making you site interactive through Ajax … I have listed them on this page http://jquer.in/?s=ajax