jQuery: a Flickr gallery with JSONP

In this post I'm going to show you how to create a simple Flickr gallery with jQuery and JSONP. JSONP stands for JSON with Padding and allows you to execute cross-domain AJAX requests using JavaScript (in this case, jQuery). We're going to use the public JSON feed of Flickr to display a simple gallery made up of nine pictures. First of all, let's take a look at the inner structure of a JSON Flickr feed:

jsonFlickrFeed({
  "title": "Recent Uploads tagged tree",
  "link": "http://www.flickr.com/photos/tags/tree/",
  "description": "",
  "modified": "2011-04-17T15:00:36Z",
  "generator": "http://www.flickr.com/",
  "items": [
    {
   "title": "River Ouse at Oakley",
   "link": "http://www.flickr.com/photos/61317049@N04/5627831146/",
   "media": {"m":"http://farm6.static.flickr.com/5149/5627831146_fd4bac3b56_m.jpg"},
   "date_taken": "2011-04-17T12:14:29-08:00",
   "description": "...",
   "published": "2011-04-17T15:00:36Z",
   "author": "nobody@flickr.com (CWigs)",
   "author_id": "61317049@N04",
   "tags": "reflection tree river bedfordshire ouse oakley"
    },
    
    // more items
     ]
})

This is a normal JSON file, except for the padding keyword added at the beginning of it, namely jsonFlickrFeed. Inside this global object there is the items array which, in turn, contains a series of objects with the relevant information about each image. These objects include:

  • link: the link of the picture page
  • media: this object contains the m property, which is the physical link to the actual image.

The first thing we need is the URL of that feed. In this case, it is as follows:

http://api.flickr.com/services/feeds/photos_public.gne?tags=tree&format=json&jsoncallback=?

The final substring &jsoncallback=? specifies that we're using JSONP. With jQuery, we only need to use $.getJSON() as follows:

$(function() {

var flickrBaseURL = 'http://api.flickr.com/services/feeds/photos_public.gne?tags=tree&format=json&jsoncallback=?';
  
  $.getJSON(flickrBaseURL, function(data){
  
    $.each(data.items, function(i, item){
      $('<img/>').attr('src', item.media.m).appendTo('#flickr')
      .wrap('<a href="' + item.link + '"></a>');
      
      return i < 8;
      
    });
    
  });
  

});

We use the $.each() utility to iterate over the items array of our JSON object (data). Since we want to include only the first nine images, we make this method to return an index value less than 8 (jQuery indexes start at 0). On each item, we retrieve only the link of the page and the path of the image by accessing the link and media.m properties, respectively. You can see a demo below.

Demo

Live demo

2 thoughts on “jQuery: a Flickr gallery with JSONP”

Leave a Reply

Note: Only a member of this blog may post a comment.