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.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 <!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>

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 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.



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.



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.

The 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.

In this property we can specify whether this will be a or a request. is used for simple data retrieval while 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.

The 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.

The 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.

The 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

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 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.

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.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 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.

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

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 <!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>

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 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.

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.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 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" : " <p><a href=" http : //www.flickr.com/people/deguet/">coralynes</a> posted a photo:</p> <p><a href="http://www.flickr.com/photos/deguet/14293974855/" title="lost in the city of angels"><img src="http://farm3.staticflickr.com/2909/14293974855_6d15767781_m.jpg" width="240" height="160" alt="lost in the city of angels" /></a></p> <p></p>", "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" : " <p><a href=" http : //www.flickr.com/people/nilspix/">NilsPix</a> posted a photo:</p> <p><a href="http://www.flickr.com/photos/nilspix/14292026192/" title=""><img src="http://farm4.staticflickr.com/3825/14292026192_b4edab6898_m.jpg" width="240" height="161" alt="" /></a></p> ", "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" : " <p><a href=" http : //www.flickr.com/people/freshairphotography/">Freshairphotography</a> posted a photo:</p> <p><a href="http://www.flickr.com/photos/freshairphotography/14290639751/" title="Ucluelet, BC - View from the Black Rock Resort"><img src="http://farm4.staticflickr.com/3779/14290639751_4a75069b14_m.jpg" width="160" height="240" alt="Ucluelet, BC - View from the Black Rock Resort" /></a></p> <p>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!</p>", "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" : " <p><a href=" http : //www.flickr.com/people/fortheride/">Kraften</a> posted a photo:</p> <p><a href="http://www.flickr.com/photos/fortheride/14314138973/" title="Might as well"><img src="http://farm3.staticflickr.com/2907/14314138973_9f32e94784_m.jpg" width="240" height="135" alt="Might as well" /></a></p> <p>Dolphins jumping off the coast via 500px <a href="http://ift.tt/1itp09r" rel="nofollow">ift.tt/1itp09r</a></p>", "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" : " <p><a href=" http : //www.flickr.com/people/darrenbarnes/">Dwood Photography</a> posted a photo:</p> <p><a href="http://www.flickr.com/photos/darrenbarnes/14107447127/" title="Placid Pacific"><img src="http://farm6.staticflickr.com/5474/14107447127_63625f9399_m.jpg" width="240" height="152" alt="Placid Pacific" /></a></p> <p>Looking out onto the <a href="http://en.wikipedia.org/wiki/Pacific_Ocean" rel="nofollow">mighty Pacific Ocean</a>. On this evening it had a placid feel about it.<br /> <br /> This shot was taken 12 mins prior to this <a href="https://www.flickr.com/photos/darrenbarnes/14208163233/in/photostream/">previous post</a>. 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.<br /> <br /> Thanks for looking.<br /> _________________________________________________________________<br /> Comments and constructive criticism always appreciated.<br /> <a href="http://en.flickeflu.com/photos/9828874@N02" rel="nofollow">Stream on Black</a>....<a href="http://www.facebook.com/DwoodPhotography" rel="nofollow">Follow on Facebook</a>....<a href="http://www.flickr.com/people/darrenbarnes/">My Profile (to get to webpage)</a></p>", "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" : " <p><a href=" http : //www.flickr.com/people/pavlinajane/">pavlinajane</a> posted a photo:</p> <p><a href="http://www.flickr.com/photos/pavlinajane/14107296278/" title="Fishing Boat"><img src="http://farm4.staticflickr.com/3825/14107296278_aac9856567_m.jpg" width="240" height="160" alt="Fishing Boat" /></a></p> ", "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" : " <p><a href=" http : //www.flickr.com/people/82955120@N05/">Free HDR & Photomanipulations - www.freestock.ca</a> posted a photo:</p> <p><a href="http://www.flickr.com/photos/82955120@N05/14270818136/" title="San Francisco Sunrise - HDR"><img src="http://farm4.staticflickr.com/3807/14270818136_2eb320ae8d_m.jpg" width="240" height="160" alt="San Francisco Sunrise - HDR" /></a></p> <p>Early morning photo of San Francisco, California (USA), as seen from Twin Peaks. HDR composite from multiple exposures.<br /> <br /> 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 <b><a href="http://freestock.ca/americas_g98-san_francisco_sunrise__hdr_p4613.html" target="_blank" rel="nofollow noopener noreferrer">same free image</a></b> from my website, <b><a href="http://www.freestock.ca" target="_blank" rel="nofollow noopener noreferrer">www.freestock.ca</a></b></p>", "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" : " <p><a href=" http : //www.flickr.com/people/pavlinajane/">pavlinajane</a> posted a photo:</p> <p><a href="http://www.flickr.com/photos/pavlinajane/14293878425/" title="Hastings view"><img src="http://farm4.staticflickr.com/3795/14293878425_a2f481d29b_m.jpg" width="240" height="160" alt="Hastings view" /></a></p> ", "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" : " <p><a href=" http : //www.flickr.com/people/whitcomberd/">WhitcombeRD</a> posted a photo:</p> <p><a href="http://www.flickr.com/photos/whitcomberd/14107266438/" title="Coral Grouper at Seaventures rig"><img src="http://farm4.staticflickr.com/3748/14107266438_828b0892fe_m.jpg" width="240" height="190" alt="Coral Grouper at Seaventures rig" /></a></p> <p>Coral Grouper and glassfish around an underwater wreck</p>", "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" : " <p><a href=" http : //www.flickr.com/people/102476184@N02/">johnr.pleak</a> posted a photo:</p> <p><a href="http://www.flickr.com/photos/102476184@N02/14314112073/" title="Riverbed by John R. Pleak"><img src="http://farm4.staticflickr.com/3695/14314112073_fcb1f13279_m.jpg" width="179" height="240" alt="Riverbed by John R. Pleak" /></a></p> <p>Digital photograph of a riverbed by John R. Pleak 2014</p>", "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" : " <p><a href=" http : //www.flickr.com/people/pavlinajane/">pavlinajane</a> posted a photo:</p> <p><a href="http://www.flickr.com/photos/pavlinajane/14314022953/" title="House Rose door"><img src="http://farm4.staticflickr.com/3730/14314022953_50563b047e_m.jpg" width="160" height="240" alt="House Rose door" /></a></p> ", "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" : " <p><a href=" http : //www.flickr.com/people/ulfurbjornsson/">Úlfur Björnsson</a> posted a photo:</p> <p><a href="http://www.flickr.com/photos/ulfurbjornsson/14290465641/" title="B&W Clouds"><img src="http://farm4.staticflickr.com/3669/14290465641_676136c7b1_m.jpg" width="240" height="183" alt="B&W Clouds" /></a></p> <p>Faroe Islands trip, 14th-20th of May.</p>", "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" : " <p><a href=" http : //www.flickr.com/people/109773589@N08/">pakhouse@att.net</a> posted a photo:</p> <p><a href="http://www.flickr.com/photos/109773589@N08/14107071629/" title="Seafaring Mallard"><img src="http://farm3.staticflickr.com/2916/14107071629_d8ab57db01_m.jpg" width="240" height="184" alt="Seafaring Mallard" /></a></p> ", "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" : " <p><a href=" http : //www.flickr.com/people/curseshadow/">Zulhatfi Aziz Photography</a> posted a photo:</p> <p><a href="http://www.flickr.com/photos/curseshadow/14293297064/" title="Pulau Sabang Seascape"><img src="http://farm4.staticflickr.com/3735/14293297064_dd773d34be_m.jpg" width="156" height="240" alt="Pulau Sabang Seascape" /></a></p> <p>Taken using : Nikon D700 + Nikon 16-35mm f4 + Schneider 10 stops ND filter.<br /> <br /> <br /> Appreciate if you can show your support by clicking the 'Like'<br /> button on my facebook page. <a href="http://www.facebook.com/zulhatfiazizphotography" rel="nofollow">www.facebook.com/zulhatfiazizphotography</a><br /> <br /> <br /> This is my official website & twitter<br /> <a href="http://www.curseshadow.com" rel="nofollow">www.curseshadow.com</a><br /> <a href="http://www.twitter.com/zulhatfiaziz" rel="nofollow">www.twitter.com/zulhatfiaziz</a><br /> <br /> <br /> I hope you're not using this image on any websites, blogs or any media<br /> without my permission. © All rights reserved. This picture is taken in<br /> only single shot. No HDR technique in this image.</p>", "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" : " <p><a href=" http : //www.flickr.com/people/88642461@N05/">darla96</a> posted a photo:</p> <p><a href="http://www.flickr.com/photos/88642461@N05/14038591469/" title="Moments In LOve"><img src="http://farm6.staticflickr.com/5567/14038591469_ed55e1da46_m.jpg" width="240" height="149" alt="Moments In LOve" /></a></p> <p>Moments in love...Quiet Storm Remix here<br /> <a href="http://www.youtube.com/watch?v=u32NM_2wq34" rel="nofollow">www.youtube.com/watch?v=u32NM_2wq34</a><br /> <br /> <a href="http://www.cameralenscompare.com/photoAwardsCounterDetails.aspx?PhotoId=14038591469&user=darla96" rel="nofollow">www.cameralenscompare.com/photoAwardsCounterDetails.aspx?...</a></p>", "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" : " <p><a href=" http : //www.flickr.com/people/88642461@N05/">darla96</a> posted a photo:</p> <p><a href="http://www.flickr.com/photos/88642461@N05/14292096874/" title="Moonlight Mile"><img src="http://farm6.staticflickr.com/5117/14292096874_4ac89f3715_m.jpg" width="240" height="109" alt="Moonlight Mile" /></a></p> ", "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" : " <p><a href=" http : //www.flickr.com/people/88642461@N05/">darla96</a> posted a photo:</p> <p><a href="http://www.flickr.com/photos/88642461@N05/9213109880/" title="The Depth of My Soul"><img src="http://farm6.staticflickr.com/5527/9213109880_4ef542762d_m.jpg" width="240" height="99" alt="The Depth of My Soul" /></a></p> <p><a href="http://www.cameralenscompare.com/photoAwardsCounterDetails.aspx?PhotoId=9213109880&user=darla96" rel="nofollow">www.cameralenscompare.com/photoAwardsCounterDetails.aspx?...</a></p>", "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" : " <p><a href=" http : //www.flickr.com/people/88642461@N05/">darla96</a> posted a photo:</p> <p><a href="http://www.flickr.com/photos/88642461@N05/14273445203/" title="Are You Game?"><img src="http://farm3.staticflickr.com/2900/14273445203_afcc9f84da_m.jpg" width="240" height="116" alt="Are You Game?" /></a></p> <p><a href="http://www.cameralenscompare.com/photoAwardsCounterDetails.aspx?PhotoId=14273445203&user=darla96" rel="nofollow">www.cameralenscompare.com/photoAwardsCounterDetails.aspx?...</a></p>", "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" : " <p><a href=" http : //www.flickr.com/people/88642461@N05/">darla96</a> posted a photo:</p> <p><a href="http://www.flickr.com/photos/88642461@N05/14020491819/" title="Heaven's Hell"><img src="http://farm6.staticflickr.com/5503/14020491819_f48384a86a_m.jpg" width="240" height="104" alt="Heaven's Hell" /></a></p> <p><a href="http://www.cameralenscompare.com/photoAwardsCounterDetails.aspx?PhotoId=14020491819&user=darla96" rel="nofollow">www.cameralenscompare.com/photoAwardsCounterDetails.aspx?...</a></p>", "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" : " <p><a href=" http : //www.flickr.com/people/mohan_berg/">discovery720266</a> posted a photo:</p> <p><a href="http://www.flickr.com/photos/mohan_berg/14107058739/" title="vīvere"><img src="http://farm3.staticflickr.com/2900/14107058739_24427401c4_m.jpg" width="240" height="120" alt="vīvere" /></a></p> <p>NOTE: All credit goes to the original photographer at 500px! " via 500px <a href="http://ift.tt/1kIVsZV"" rel="nofollow">ift.tt/1kIVsZV"</a>;</p>", "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.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 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.





$.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.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 <!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>

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 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 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.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 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!

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!