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.

<!doctype html>
<html>

<head>
 <meta charset="utf-8">
 <title>jQuery Event Handling</title>
 <link rel="stylesheet" href="bootstrap/css/bootstrap.css">
</head>

<body class="container">
 <p></p>
 <div id="content" class="jumbotron">
  <span id="click" class="btn btn-primary">Run AJAX!</span>
 </div>

 <div class="alert">
 </div>

 <script src="jquery-1.11.1.js"></script>
 <!-- Include all compiled plugins (below), or include individual files as needed -->
 <script src="bootstrap/js/bootstrap.js"></script>
 <!-- custom written js -->
 <script src="tut.js"></script>
</body>

</html>
jQuery(document).ready(function($){

 function getText() {
  $.ajax({
   // the URL for the request
   url: 'sometext.txt',

   // whether this is a POST or GET request
   type: 'GET',

   // the type of data we expect back
   dataType: 'text',

   // function to call for success
   success: successFunction,

   // function to call on an error
   error: errorFunction,

   // code to run regardless of success or failure
   complete: function (xhr, status) {
    jQuery('.alert').append('<strong>Status: ' + status + '</strong>' + ' Your request is finished!');
    jQuery('#click').addClass('disabled');
   }
  });
 }

 function successFunction(result) {
  jQuery('#content').append(result);
 }

 function errorFunction(xhr, status, strErr) {
  jQuery('#content').append(strErr);
 }
 
 jQuery('#click').click(function () {
  getText();
 });

});

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

jQuery(document).ready(function($){

 function getText() {
  $.get('sometext.txt', successFunction);
  jQuery('#click').addClass('disabled');
 }

 function successFunction(result) {
  jQuery('#content').append(result);
 }

 jQuery('#click').click(function () {
  getText();
 });

 $.ajaxSetup({
  // Disable caching of AJAX responses
  cache: false
 });

});

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.

jQuery(document).ready(function($){

 function getText() {
  jQuery('#content').load('sometext.txt');
 }

 jQuery('#click').click(function () {
  getText();
 });

 $.ajaxSetup({
  // Disable caching of AJAX responses
  cache: false
 });

});

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();

<!doctype html>
<html>

<head>
 <meta charset="utf-8">
 <title>jQuery Event Handling</title>
 <link rel="stylesheet" href="bootstrap/css/bootstrap.css">
</head>

<body class="container">
 <p></p>
 <span id="click" class="btn btn-primary">Fetch Data From Flickr!</span>
 <p></p>
 <div id="content" class="jumbotron">

 </div>

 <div class="alert">
 </div>

 <script src="jquery-1.11.1.js"></script>
 <!-- Include all compiled plugins (below), or include individual files as needed -->
 <script src="bootstrap/js/bootstrap.js"></script>
 <!-- custom written js -->
 <script src="tut.js"></script>
</body>

</html>
jQuery(document).ready(function($){

 function fetchFlickrJSONData() {
  var flickrAPI = 'http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?';
  $.getJSON(flickrAPI, {
    tags: 'Ocean',
    tagmode: 'any',
    format: 'json'
   },
   successFunction);
 }

 function successFunction(result) {
  $.each(result.items, function (i, item) {
   jQuery('<img>').attr('src', item.media.m).appendTo('#content');
  });
 }

 function errorFunction(xhr, status, strErr) {
  alert(strErr);
 }

 jQuery('#click').click(function () {
  fetchFlickrJSONData();
 });

 $.ajaxSetup({
  // Disable caching of AJAX responses
  cache: false
 });

});

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.

jQuery111104020101139715232_1401317867081({
   "title":"Recent Uploads tagged ocean",
   "link":"http://www.flickr.com/photos/tags/ocean/",
   "description":"",
   "modified":"2014-05-28T22:53:31Z",
   "generator":"http://www.flickr.com/",
   "items":[
      {
         "title":"lost in the city of angels",
         "link":"http://www.flickr.com/photos/deguet/14293974855/",
         "media":{
            "m":"http://farm3.staticflickr.com/2909/14293974855_6d15767781_m.jpg"
         },
         "date_taken":"2009-05-26T23:45:39-08:00",
         "description":" 

coralynes posted a photo:

lost in the city of angels

", "published":"2014-05-28T22:53:31Z", "author":"nobody@flickr.com (coralynes)", "author_id":"54978430@N07", "tags":"ocean city sky aracaju sergipe" }, { "title":"", "link":"http://www.flickr.com/photos/nilspix/14292026192/", "media":{ "m":"http://farm4.staticflickr.com/3825/14292026192_b4edab6898_m.jpg" }, "date_taken":"2014-05-26T07:50:28-08:00", "description":"

NilsPix posted a photo:

", "published":"2014-05-28T22:50:26Z", "author":"nobody@flickr.com (NilsPix)", "author_id":"74997357@N03", "tags":"ocean sea beach clouds sand surf longisland shore jonesbeach" }, { "title":"Ucluelet, BC - View from the Black Rock Resort", "link":"http://www.flickr.com/photos/freshairphotography/14290639751/", "media":{ "m":"http://farm4.staticflickr.com/3779/14290639751_4a75069b14_m.jpg" }, "date_taken":"2014-05-26T17:34:36-08:00", "description":"

Freshairphotography posted a photo:

Ucluelet, BC - View from the Black Rock Resort

Looking directly out to the Pacific from our room at the Black Rock Resort was such a feast for the eyes. Listening to the waves crashing along the shoreline rocks/bluffs - the sea birds singing and calling out to each other - pure bliss for 2 days!

", "published":"2014-05-28T22:56:11Z", "author":"nobody@flickr.com (Freshairphotography)", "author_id":"93408882@N03", "tags":"ocean blue trees light sunlight canada tree tourism beach nature colors beautiful beauty clouds forest canon island evening coast amazing interesting rainforest rocks bc view natural pacific hiking path relaxing trails peaceful sealife tourist hike vancouverisland trail pacificocean views windswept greens tofino serene westcoast tidal ucluelet nationalgeographic crashingwaves rockformation oceanspray oldgrowthforest beautifulbc blackrockresort explorebc canon7d explorecanada ilovebc explorevancouverisland" }, { "title":"Might as well", "link":"http://www.flickr.com/photos/fortheride/14314138973/", "media":{ "m":"http://farm3.staticflickr.com/2907/14314138973_9f32e94784_m.jpg" }, "date_taken":"2014-05-18T13:37:17-08:00", "description":"

Kraften posted a photo:

Might as well

Dolphins jumping off the coast via 500px ift.tt/1itp09r

", "published":"2014-05-28T22:42:23Z", "author":"nobody@flickr.com (Kraften)", "author_id":"94135442@N00", "tags":"ocean california sea water animals swim pacific dolphins 500px ifttt" }, { "title":"Placid Pacific", "link":"http://www.flickr.com/photos/darrenbarnes/14107447127/", "media":{ "m":"http://farm6.staticflickr.com/5474/14107447127_63625f9399_m.jpg" }, "date_taken":"2014-04-28T18:50:20-08:00", "description":"

Dwood Photography posted a photo:

Placid Pacific

Looking out onto the mighty Pacific Ocean. On this evening it had a placid feel about it.

This shot was taken 12 mins prior to this previous post. I usually prefer a stronger foreground element in my beach scenes, but sometimes you just have to work with what you have, and in this case I thought the sun glow on the sand served as a nice focal point.

Thanks for looking.
_________________________________________________________________
Comments and constructive criticism always appreciated.
Stream on Black....Follow on Facebook....My Profile (to get to webpage)

", "published":"2014-05-28T22:49:10Z", "author":"nobody@flickr.com (Dwood Photography)", "author_id":"9828874@N02", "tags":"ocean california ca pink blue seascape yellow landscape sand pacific pacificocean placid dwoodphotography dwoodphotographycom placidpacific" }, { "title":"Fishing Boat", "link":"http://www.flickr.com/photos/pavlinajane/14107296278/", "media":{ "m":"http://farm4.staticflickr.com/3825/14107296278_aac9856567_m.jpg" }, "date_taken":"2014-05-28T10:40:27-08:00", "description":"

pavlinajane posted a photo:

Fishing Boat

", "published":"2014-05-28T22:42:27Z", "author":"nobody@flickr.com (pavlinajane)", "author_id":"60291025@N05", "tags":"ocean old travel blue sunset sea summer vacation sky white lake fish male net industry beach nature water silhouette sport illustration river landscape evening coast harbor boat fishing fisherman marine ship outdoor seagull horizon transport wave vessel hobby line commercial shore transportation rod catch leisure recreation hastings nautical activity fishingboat vector trawler reel" }, { "title":"San Francisco Sunrise - HDR", "link":"http://www.flickr.com/photos/82955120@N05/14270818136/", "media":{ "m":"http://farm4.staticflickr.com/3807/14270818136_2eb320ae8d_m.jpg" }, "date_taken":"2013-12-29T07:54:20-08:00", "description":"

Free HDR & Photomanipulations - www.freestock.ca posted a photo:

San Francisco Sunrise - HDR

Early morning photo of San Francisco, California (USA), as seen from Twin Peaks. HDR composite from multiple exposures.

This photo is released under a standard Creative Commons License - Attribution 3.0 Unported. It gives you a lot of freedom to use my work commercially as long as you credit and link back to the same free image from my website, www.freestock.ca

", "published":"2014-05-28T22:42:10Z", "author":"nobody@flickr.com (Free HDR & Photomanipulations - www.freestock.ca)", "author_id":"82955120@N05", "tags":"ocean california road street city morning travel bridge trees sea sky urban usa sun mountain streets building tree tourism water beautiful beauty grass architecture america sunrise buildings river landscape outside outdoors dawn bay early us construction scenery san francisco glow cityscape exterior angle pacific image outdoor united stock wide scenic picture landmarks free twin wideangle landmark scene architectural line hills foliage american nicolas transportation area glowing raymond states roads peaks rise hdr resource cityline somadjinn" }, { "title":"Hastings view", "link":"http://www.flickr.com/photos/pavlinajane/14293878425/", "media":{ "m":"http://farm4.staticflickr.com/3795/14293878425_a2f481d29b_m.jpg" }, "date_taken":"2014-05-28T10:27:42-08:00", "description":"

pavlinajane posted a photo:

Hastings view

", "published":"2014-05-28T22:31:16Z", "author":"nobody@flickr.com (pavlinajane)", "author_id":"60291025@N05", "tags":"ocean trip travel blue sunset sea summer vacation sky sun holiday fish seascape tourism beach nature water beautiful architecture port relax landscape outdoors island bay coast harbor boat town seaside fishing fisherman sand scenery europe paradise mediterranean ship view yacht outdoor turquoise horizon scenic wave sunny coastal shore coastline recreation hastings idyllic tranquil hastingscoast hastingsboat finingboat" }, { "title":"Coral Grouper at Seaventures rig", "link":"http://www.flickr.com/photos/whitcomberd/14107266438/", "media":{ "m":"http://farm4.staticflickr.com/3748/14107266438_828b0892fe_m.jpg" }, "date_taken":"2014-04-23T13:00:11-08:00", "description":"

WhitcombeRD posted a photo:

Coral Grouper at Seaventures rig

Coral Grouper and glassfish around an underwater wreck

", "published":"2014-05-28T22:34:40Z", "author":"nobody@flickr.com (WhitcombeRD)", "author_id":"8705027@N03", "tags":"ocean life blue school red sea wild fish seascape color nature water animal coral metal marine colorful aqua asia soft underwater wildlife debris bottom under pipe egypt conservation tire scuba diving artificial snorkeling exotic pollution malaysia tropical manmade environment caribbean aquatic wreck reef wreckage tyres biodiversity grouper shoal encrusted glassfish" }, { "title":"Riverbed by John R. Pleak", "link":"http://www.flickr.com/photos/102476184@N02/14314112073/", "media":{ "m":"http://farm4.staticflickr.com/3695/14314112073_fcb1f13279_m.jpg" }, "date_taken":"2014-05-28T15:52:17-08:00", "description":"

johnr.pleak posted a photo:

Riverbed by John R. Pleak

Digital photograph of a riverbed by John R. Pleak 2014

", "published":"2014-05-28T22:38:50Z", "author":"nobody@flickr.com (johnr.pleak)", "author_id":"102476184@N02", "tags":"ocean sea art nature water creek river fishing stream artist underwater wildlife scubadiving nationalgeographic marinelife 2014 scubadiver curent johnrpleak johnpleak" }, { "title":"House Rose door", "link":"http://www.flickr.com/photos/pavlinajane/14314022953/", "media":{ "m":"http://farm4.staticflickr.com/3730/14314022953_50563b047e_m.jpg" }, "date_taken":"2014-05-28T10:19:47-08:00", "description":"

pavlinajane posted a photo:

House Rose door

", "published":"2014-05-28T22:21:40Z", "author":"nobody@flickr.com (pavlinajane)", "author_id":"60291025@N05", "tags":"ocean sea wild food white fish cooking water animal rose illustration dinner emblem menu lunch cuisine restaurant lemon healthy fishing marine mediterranean raw dish market eating background label tag salmon rubber fresh rye stamp gourmet business delicious eat meal seafood catch diet cooked rosegarden vector culinary isolated preparation freshness saltwater nutrition ingredient prepared rosehouse rosedoor roseuk ryerosedoor" }, { "title":"B&W Clouds", "link":"http://www.flickr.com/photos/ulfurbjornsson/14290465641/", "media":{ "m":"http://farm4.staticflickr.com/3669/14290465641_676136c7b1_m.jpg" }, "date_taken":"2014-05-16T16:35:23-08:00", "description":"

Úlfur Björnsson posted a photo:

B&W Clouds

Faroe Islands trip, 14th-20th of May.

", "published":"2014-05-28T22:26:44Z", "author":"nobody@flickr.com (Úlfur Björnsson)", "author_id":"45906481@N08", "tags":"ocean trip sea summer vacation bw white black rain clouds canon landscape islands faroe 6d 70200mm færeyjar úlfur" }, { "title":"Seafaring Mallard", "link":"http://www.flickr.com/photos/109773589@N08/14107071629/", "media":{ "m":"http://farm3.staticflickr.com/2916/14107071629_d8ab57db01_m.jpg" }, "date_taken":"2014-05-24T02:27:44-08:00", "description":"

pakhouse@att.net posted a photo:

Seafaring Mallard

", "published":"2014-05-28T22:13:06Z", "author":"nobody@flickr.com (pakhouse@att.net)", "author_id":"109773589@N08", "tags":"ocean duck flight mallard seashore" }, { "title":"Pulau Sabang Seascape", "link":"http://www.flickr.com/photos/curseshadow/14293297064/", "media":{ "m":"http://farm4.staticflickr.com/3735/14293297064_dd773d34be_m.jpg" }, "date_taken":"2014-05-14T19:44:08-08:00", "description":"

Zulhatfi Aziz Photography posted a photo:

Pulau Sabang Seascape

Taken using : Nikon D700 + Nikon 16-35mm f4 + Schneider 10 stops ND filter.


Appreciate if you can show your support by clicking the 'Like'
button on my facebook page. www.facebook.com/zulhatfiazizphotography


This is my official website & twitter
www.curseshadow.com
www.twitter.com/zulhatfiaziz


I hope you're not using this image on any websites, blogs or any media
without my permission. © All rights reserved. This picture is taken in
only single shot. No HDR technique in this image.

", "published":"2014-05-28T22:19:22Z", "author":"nobody@flickr.com (Zulhatfi Aziz Photography)", "author_id":"10860615@N04", "tags":"ocean trip travel light sunset sea summer vacation sky blackandwhite bw white holiday seascape motion black color beach water rain weather clouds port indonesia lens landscape island photography dawn evening coast photo sand nikon long exposure waves colours outdoor south hard scenic dramatic places explore southern tsunami filter malaysia langkawi rise dickson aceh heavy grad raining pulau aziz ache sabang atjeh singhray d700 zulhatfi zulhatfiaziz" }, { "title":"Moments In LOve", "link":"http://www.flickr.com/photos/88642461@N05/14038591469/", "media":{ "m":"http://farm6.staticflickr.com/5567/14038591469_ed55e1da46_m.jpg" }, "date_taken":"2014-05-19T17:35:55-08:00", "description":"

darla96 posted a photo:

Moments In LOve

Moments in love...Quiet Storm Remix here
www.youtube.com/watch?v=u32NM_2wq34

www.cameralenscompare.com/photoAwardsCounterDetails.aspx?...

", "published":"2014-05-28T22:07:50Z", "author":"nobody@flickr.com (darla96)", "author_id":"88642461@N05", "tags":"ocean girls art beach water photoshop model waves arty phone florida miami models creative babe concept bathing mermaid darla tanning sunning celll darla96" }, { "title":"Moonlight Mile", "link":"http://www.flickr.com/photos/88642461@N05/14292096874/", "media":{ "m":"http://farm6.staticflickr.com/5117/14292096874_4ac89f3715_m.jpg" }, "date_taken":"2014-05-28T14:24:52-08:00", "description":"

darla96 posted a photo:

Moonlight Mile

", "published":"2014-05-28T22:07:59Z", "author":"nobody@flickr.com (darla96)", "author_id":"88642461@N05", "tags":"ocean sea woman white black sexy art beach water swim photoshop pose model sand shoot waves arty photoshoot body creative babe moonlight concept darla mile darla96" }, { "title":"The Depth of My Soul", "link":"http://www.flickr.com/photos/88642461@N05/9213109880/", "media":{ "m":"http://farm6.staticflickr.com/5527/9213109880_4ef542762d_m.jpg" }, "date_taken":"2013-07-04T20:35:38-08:00", "description":"

darla96 posted a photo:

The Depth of My Soul

www.cameralenscompare.com/photoAwardsCounterDetails.aspx?...

", "published":"2014-05-28T22:07:53Z", "author":"nobody@flickr.com (darla96)", "author_id":"88642461@N05", "tags":"ocean light sky sun art water clouds photoshop arty legs creative soul a3 concept darla начинизавиждане blinkagain darla96 infinitexposurel1p1" }, { "title":"Are You Game?", "link":"http://www.flickr.com/photos/88642461@N05/14273445203/", "media":{ "m":"http://farm3.staticflickr.com/2900/14273445203_afcc9f84da_m.jpg" }, "date_taken":"2014-05-23T18:40:03-08:00", "description":"

darla96 posted a photo:

Are You Game?

www.cameralenscompare.com/photoAwardsCounterDetails.aspx?...

", "published":"2014-05-28T22:07:54Z", "author":"nobody@flickr.com (darla96)", "author_id":"88642461@N05", "tags":"ocean girls art beach water photoshop model waves arty phone florida miami models creative babe bikini spitfire concept bathing mermaid darla tanning vollyball sunning celll darla96" }, { "title":"Heaven's Hell", "link":"http://www.flickr.com/photos/88642461@N05/14020491819/", "media":{ "m":"http://farm6.staticflickr.com/5503/14020491819_f48384a86a_m.jpg" }, "date_taken":"2014-05-17T15:01:11-08:00", "description":"

darla96 posted a photo:

Heaven's Hell

www.cameralenscompare.com/photoAwardsCounterDetails.aspx?...

", "published":"2014-05-28T22:07:48Z", "author":"nobody@flickr.com (darla96)", "author_id":"88642461@N05", "tags":"ocean morning sea sky sun seascape color art beach water sunshine clouds photoshop skulls fire death sand heaven waves arty god hell creative vivid blessing soul concept rise darla revolt sunscape darla96" }, { "title":"vīvere", "link":"http://www.flickr.com/photos/mohan_berg/14107058739/", "media":{ "m":"http://farm3.staticflickr.com/2900/14107058739_24427401c4_m.jpg" }, "date_taken":"2014-05-28T18:01:56-08:00", "description":"

discovery720266 posted a photo:

vīvere

NOTE: All credit goes to the original photographer at 500px! " via 500px ift.tt/1kIVsZV";

", "published":"2014-05-28T22:01:56Z", "author":"nobody@flickr.com (discovery720266)", "author_id":"96723055@N08", "tags":"ocean sea woman female clouds hawaii underwater dreamy form 500px ifttt" } ] })

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.

function fetchFlickrJSONData() {
  var flickrAPI = 'http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?';
  $.getJSON(flickrAPI, {
    tags: 'Ocean',
    tagmode: 'any',
    format: 'json'
   },
   successFunction);
 }

 function successFunction(result) {
  $.each(result.items, function (i, item) {
   var title = item.title;
   var link = item.link;
   var imgsrc = item.media.m;
   var image = '<a href="' + link + '" title="' + title + '"><img src="' + imgsrc + '" /></a>';
   $(image).appendTo('#content');
  });
 }

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.

<!doctype html>
<html>

<head>
 <meta charset="utf-8">
 <title>jQuery Event Handling</title>
 <link rel="stylesheet" href="bootstrap/css/bootstrap.css">
</head>

<body class="container">
 <p></p>
 <span id="click" class="btn btn-primary">Fetch XML Data!</span>
 <p></p>
 <div id="content" class="jumbotron">

 </div>

 <div class="alert">
 </div>

 <script src="jquery-1.11.1.js"></script>
 <!-- Include all compiled plugins (below), or include individual files as needed -->
 <script src="bootstrap/js/bootstrap.js"></script>
 <!-- custom written js -->
 <script src="tut.js"></script>
</body>

</html>
jQuery(document).ready(function($){

 function fetchXMLData() {
  $.get('xmldata.xml', function (result) {
   var website = result.getElementsByTagName('website')[0];
   var about = result.getElementsByTagName('about')[0];
   var val = 'What is this VegiBit you speak of? <b>' + website.firstChild.nodeValue + '</b> ' + about.firstChild.nodeValue;
   jQuery('#content').append(val);
  });
 }

 jQuery('#click').click(function () {
  fetchXMLData();
 });

 $.ajaxSetup({
  // Disable caching of AJAX responses
  cache: false
 });

});

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.

jQuery(document).ready(function($){

 function fetchXMLData() {
  $.get('xmldata.xml', function (result) {
   var website = result.getElementsByTagName('website')[0];
   var about = result.getElementsByTagName('about')[0];
   var val = 'What is this VegiBit you speak of? <b>' + website.firstChild.nodeValue + '</b> ' + about.firstChild.nodeValue;
   jQuery('#content').append(val);
  });
 }

 jQuery('#click').click(function () {
  fetchXMLData();
 });

 $.ajaxSetup({
  // Disable caching of AJAX responses
  cache: false
 });

 $(document).ajaxStart(function () {
  jQuery('<div class="alert alert-info">Ajax has started!</div>').insertAfter('#content');
 });

 $(document).ajaxStop(function () {
  jQuery('<div class="alert alert-danger">Ajax has ended!</div>').insertAfter('#content');
 });

 $(document).ajaxSend(function () {
  jQuery('<div class="alert alert-warning">Ajax is requesting the data now!</div>').insertAfter('#content');
 });

 $(document).ajaxComplete(function () {
  jQuery('<div class="alert alert-success">The full AJAX life cycle is now complete!</div>').insertAfter('#content');
 });

 $(document).ajaxError(function (evt, jqXHR, settings, err) {
  jQuery('<div class="alert alert-danger">Oh no, there must have been an error! ' + err + '</div>').insertAfter('#content');
 });

 $(document).ajaxSuccess(function () {
  console.log("Looks like everything worked!");
 });

});

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!