|

jQuery AJAX Tutorial

jquery

AJAX is in use all over the internet today. By using AJAX, your website can get data from remote services and communicate with your web server without a full page refresh. In recent times, AJAX has really become one of the major components of building modern web applications. It can be a little tricky to implement in native JavaScript, but by using jQuery, it does become a whole lot easier. Let’s examine how working with AJAX in jQuery can benefit you and your webpages!


The AJAX function in jQuery

The first way you can work with AJAX in jQuery is to use the actual .ajax() method in the library. The .ajax() method is more of a low level interface rather than the more simplified AJAX helper methods that we will discuss shortly. For now, let’s just whip up some code and examine how it works.

With this code in place we can test out the AJAX that gets triggered when we click the button. First we’ll just click the button to run the code and see what happens.
jquery ajax success

This looks perfect. The function is run when we click, that data is loaded into the page, the status is displayed, and the button becomes disabled to prevent multiple clicks causing the same data to load into the page over and over again. Ok, now let’s rename the text file on the sever to something else and try again. We can see the result here.
jquery ajax failure
Oh No! This time the AJAX request has failed because the file it is looking for is not there. In this case, error information is displayed to the screen based on the JavaScript we had written for a failure scenario. Note that in both instances, we leave the firebug console open and we can see the request being made of the server from the browser. You have the ability to inspect the Headers, Response, HTML, and Cookies associated with the AJAX request being made and this comes in really handy during debugging of your application.

It all works quite easily, but there is a fair amount happening in the JavaScript demo here. It pays to review how this all works. First, let’s begin with analyzing the information that we are passing to the .ajax() method. In this example, we pass 6 properties via an object to the .ajax() method. Note that items in an object appear in between { curly braces } and are separated by a comma.

  • url The url property is where we are directing this request to. This must be an url on the same domain as the current web page.
  • type In this property we can specify whether this will be a POST or a GET request. GET is used for simple data retrieval while POST would be used in form submission, database updates, or some other process that modifies data.
  • dataType The dataType property declares the type of information we are hoping to get back from our request.
  • success The success property holds a function which gets triggered upon a successful AJAX request.
  • error The error property holds a function that gets triggered if there is an error during the AJAX request.
  • complete The complete property holds holds a function which gets triggered regardless of success or failure. This function will run no matter what.

Having these properties memorized will make it easy for you to do basic ajax requests in your web application. Do note that there are tons more properties and methods to deal with when using the low level interface for AJAX requests in jQuery. If you want to just get up and running quickly however, this example here gives you a fantastic blueprint to do so.


jQuery AJAX Helper Functions

jQuery has a slew of AJAX helper functions to make dealing with AJAX even more compressed in terms of the number of lines of code that you would have to write in order to make things happen. In the first example when we used the $.ajax() method, we passed a lot of information to the method. We can rewrite this example and get the same effect more or less using the $.get() or .load() helper method. Let’s check out how to use them.

Using the jQuery $.get() Method

With this updated code, we can run the function by clicking our button and observe the result.

jquery get ajax success

Awesome! As you can see when this code ran, it was successful. That brings up a good point to note with the $.get() method! There is no way to set an error handler when using this shorthand method, you would need to use the $.ajax() method we discussed first! So you see, we do get the benefit of a more terse syntax, however if you need that granular control, it is better to use the low level function to get it done. Another point to note here is that we did make use of the $.ajaxSetup() method to turn off caching. This was so that we could change the text in our test file, and jQuery would return the new data rather than the cached version in the browser. Had we not taken this step, the text displayed on the screen would still be from the prior example and we certainly don’t want that! We can also set all of the options available in the standard $.ajax() method, so if you really want to use these shorthand methods and still have fine tuned control, you can use $.ajaxSetup() to do so.

Using the jQuery .load() Method

The action of using the $.get() method along with a user defined success function to load the response into the existing web page is very common. It is so common in fact, that jQuery provides a shorthand way to accomplish this in one step. We can rewrite our AJAX request again using this approach.

When we run the code, we can see the following result.

jquery load method

Awesome! It does work, but do you notice anything different? Yes that’s right, the button that we have been attaching a click event to is missing after we run the code. This is because, with the .load() method, any HTML or text within the specified selector will be replaced with the returned data from the AJAX call. In the other examples, the button remained because in our success function we were appending to the content, but again, with .load() content is replaced. Get It? Got It. Good!


AJAX Return Data Types in jQuery

So far we have only worked with a very simple text file on our own server. We should be a little more adventurous and try something a bit more interesting. How about fetching images from the Flickr API via AJAX and JSON? Yeah, that sounds fun! We can do just that with jQuery. Let’s see how we can do it.

$.getJSON();

If we run the example in our browser, we can see the result.

jquery getjson api

Cool! As you can see, upon clicking the button, our little web app goes out to the Flickr API and fetches a bunch of images. Those images are actually just a collection of data given to us from the Flickr API. We would need to take a look at the return result to understand how to use that information in our page.

This is the raw JSON data that the Flickr API sends to us when we click the button to fetch images.

Whoa! That’s a lot of information! It does look like a lot of information to navigate through, but it is fairly straightforward if we follow the conventions of JSON. JSON really just boils down to name / value pairs. We can see that in the items array of the returned JSON, there are many properties. It should make sense if you examine the JavaScript code what it is doing with the returned JSON data. Let’s modify our success function to use more properties from the items array so we understand exactly how to tap into each value.

This code starts by making a call to the Flickr API with the jQuery $.getJSON() method. The three parameters we pass to it are the url of the JSON API, an object containing properties of information we’d like from the API, and lastly a function to run on success. Perfect.

Inside the successFunction() we access the returned data from the JSON request and build up an image with the data we’d like, and append that to our #content div in the HTML page. The function accepts the result as it’s only parameter. The response has many items in it, so we iterate over all of them using $.each(). Note! This is not the same as $(selector).each(), which is used to iterate over a jQuery object. This version can iterate over any collection, whether it is an object or an array. The first parameter to this method is the collection of items in question, and a function to run on each iteration. The anonymous function take two parameters, the first being the index of the collection, and the second being the collection itself. In our example we use i and item to refer to each item in the collection. We could just as easily passed in tom and jerry, and it would still work so long as we reference those items using that notation within the function. Inside this function we then simply declare a few variables and populate them with the data from the returned JSON. Then we build up an image surrounded by an a tag, and append each one to the #content div in the page. This is really cool, as now when we load the data, our images will load and their title will be set, along with the ability to click on each image and view the full size original picture in all of it’s glory on the main Flickr Website. Awesome! In this example, we load some images via AJAX, then click the first image to visit Flickr.

flickr api json
flickr click through

$.getXMLData();

So we can see that fetching JSON data is pretty exciting, and we were able to build a cool application to fetch pictures from the Flickr API. jQuery also provides a way to fetch raw XML data. The data returned will be an authentic XML document, not a string representation of said data. Because of that, the standard DOM methods will work on this data. Let’s see an example of how this particular method works.

Running this method gives us this nice output as you can see.

jquery fetch XML data


jQuery AJAX Global Event Handlers

In jQuery there are several Global AJAX event handlers that can listen for AJAX requests on the page and take various actions during the various steps of an AJAX request. Remember, an event handler is not something you explicitly call, it is something that gets called for you when a particular event has taken place. This works just like many of the Native JavaScript Event Handlers. We’ll simply build on the prior example by adding several event listeners to the JavaScript code. We’ll simply insert some colorful HTML into the page each time an event listener triggers.

Bada Boom, BADA BING!

jquery ajax global event handlers

When we run the AJAX request, it may look like these things happened all at once, but in reality each event listener triggered one at a time in order and the result was inserted into the page one at a time. It just all happens so fast on a local server, that it looks immediate.

This has been a fun crash course in using the most common methods of AJAX in jQuery, I hope you enjoyed it!