How to use jQuery with a JSON Flickr feed to display photos

So today I needed to display photos from our Flickr Group without using php or asp.net. I have a WordPress widget that does this job nicely, but no PHP was allowed.

Thank goodness for jQuery! jQuery has a handy little function which allows us to load JSON data using an HTTP GET request, and then process the contents as an array. And with some natty CSS to square things up as a grid, I have nine random (ish) photos from our Flickr group displaying in a nice 3×3 grid.

See it in action.

The full commented code is at the bottom of this post, but let’s go through it bit by bit.

What is JSON?

Since we’re talking about Flickr, let’s use they’re definition:

“JSON, or JavaScript Object Notation, is a simple machine-readable data-interchange format, which makes constructing API applications in JavaScript easy (though it can be used from other languages too!). “

Which means what exactly? Well, it’s a lot like any other feed or data – like an RSS feed, for example. A typical Flick JSON response might look like this:

({
    "title": "Talk On Travel Pool",
    "link": "http://www.flickr.com/groups/talkontravel/pool/",
    "description": "Travel and vacation photos from around the world, featured on the Talk On Travel blog. Join us in sharing your favourite destinations, your top hot spots, and the places to avoid. ",
    "modified": "2009-02-02T11:10:27Z",
    "generator": "http://www.flickr.com/",
    "items": [
            {
            "title": "View from the hotel",
            "link": "http://www.flickr.com/photos/33112458@N08/3081564649/in/pool-998875@N22",
            "media": {"m":"http://farm4.static.flickr.com/3037/3081564649_4a6569750c_m.jpg"},
            "date_taken": "2008-12-04T04:43:03-08:00",
            "description": "<p><a href="http://www.flickr.com/people/33112458@N08/"> Talk On Travel</a> has added a photo to the pool:</p> <p><a href="http:// www.flickr.com/photos/33112458@N08/3081564649/" title="View from the hotel"> <img src="http://farm4.static.flickr.com/3037/3081564649_4a6569750c_m.jpg" width="240" height="180" alt="View from the hotel" /></a></p> ",
            "published": "2008-12-04T12:43:03Z",
            "author": "nobody@flickr.com (Talk On Travel)",
            "author_id": "33112458@N08",
            "tags": "spain dolphins tenerife canaries lagomera aqualand playadelasamericas junglepark losgigantos loscristines talkontravel"
            }
    ]
})

Which is not altogether too hard to digest. To see the whole feed from Talk On Travel have a look here.

All we need to do is get that feed in a way our javascript can use, and then use it. Enter, stage left, jQuery…

Create our object and fill it with data

So how can jQuery help us out? With the handy $.getJSON(url, [data], [callback]) command.

It’s simpliest method would be something like:

$.getJSON("http://www.example.com/yourjsonfeed.json", functionName);

Which would grab the info from a json feed at www.example.com/yourjsonfeed.json and then execute a function called functionName.

Then, you’d have to create a function like so:

function functionName(data) {
}

In which data is automatically populated with the json feed. Nice, eh?

So now we have our data object, we need to know how to grab stuff out of it. Again, this is pretty easy stuff. We use some dot syntax like:

data.item.media.m

Which says… in data, go to (the first) item, then go to the media bit and grab the m bit.

Scroll back to the top of this page, and in our example you’ll see that this would be ‘http://farm4.static.flickr.com/3037/3081564649_4a6569750c_m.jpg’.

You can probably work out then what item.title and item.link would give us. Armed with that, you can get any information you need from this feed. All we have to do now is display it!

Getting this feed onto the screen

Does that make sense so far? Hope so. If you get lost, check out the excellent jQuery documentation – the links for which are at the bottom of this post.

Let’s sew it all together in a really simple function that just cycles through all the images in the feed. By default, Flickr returns 20 images.

As I’ve commented the code, you should be able to work it out from here…

// Our very special jQuery JSON fucntion call to Flickr, gets details
// of the most recent 20 images

$.getJSON("http://api.flickr.com/services/feeds/groups_pool.gne?id=
998875@N22〈=en-us&amp;format=json&amp;jsoncallback=?"
, displayImages);

function displayImages(data) {

    // Start putting together the HTML string
    var htmlString = "";
   
    // Now start cycling through our array of Flickr photo details
    $.each(data.items, function(i,item){
   
        // I only want the ickle square thumbnails
        var sourceSquare = (item.media.m).replace("_m.jpg", "_s.jpg");
       
        // Here's where we piece together the HTML
        htmlString += '<li><a href="' + item.link + '" target="_blank">';
        htmlString += '<img title="' + item.title + '" src="' + sourceSquare;
        htmlString += '" alt="'; htmlString += item.title + '" />';
        htmlString += '</a></li>
        '
;
   
    });
   
    // Pop our HTML in the #images DIV
    $('#images').html(htmlString);
   
    // Close down the JSON function call
}

But those aren’t my photos!?

I know, I know. Have a look at that feed address once more…

http://api.flickr.com/services/feeds/groups_pool.gne?id=998875@N22&lang=en-us&format=json&jsoncallback=?

Spot the 998875@N22 bit? Well that’s the Flickr user ID for Talk On Travel, another blog that I look after. You need to put your own ID in that string.

I recommend using http://idgettr.com/ to find out easily!

Over to you

That’s a simple introduction to JSON and Flickr, and I hope it puts you on the right path.

For more details on JSON and jQuery, and with another example of how to get photos from a Flickr JSON feed, check out http://docs.jquery.com/Ajax/jQuery.getJSON.

To read up on the Flickr JSON object, head over to http://www.flickr.com/services/api/response.json.html.

You can see my code in action at http://www.richardshepherd.com/flickr.html. Check out the source code to see what it’s doing.

Obviously, you can do a lot more with this, but it’s just a basic implementation to get you started.

Good luck!

64 thoughts on “How to use jQuery with a JSON Flickr feed to display photos”

  1. thanks for the code.

    i am trying to put a class=”zoom” (it’s like rel=”lightbox”) on the link, but still it opens in a new window and the class doesn’t work.
    (even if i removed the target=”_blank”)

    what do i do wrong?

  2. I’m having a bit of trouble getting this working on my site. I have no experience with scripting so I can’t troubleshoot it myself.

    These are my own ideas as to why it’s not:

    My api key seems slightly different to yours other than the fact that min is from photos_public.
    Could this be the problem

    http://api.flickr.com/services/feeds/photos_public.gne?id=31654266@N02&lang=en-us&format=json&jsoncallback=?

    I’m putting this on my wordpress page but I’m not using widgets so I can’t use FlickrBox.
    Is there a specific place I need to have the script if it is to be in a sidebar or should I keep it in the head section?

    With the styling I just pasted in the code from this site. Do I have to set up div’s in my sidebar for this to work.

    I’m fairly novice at this so I’m sure half these questions are irrelevant but they were the only things I could think of.

    Thanks,

    Kilian

  3. Can this be done with a field ‘image’ Google Spreadsheet as well? I’ve tried, but I couldn’t get it to work. And spreadsheets.google.com does do json. Any ideas?

  4. The problem is that “&” is being replaced by “&” in the code upon copying. Do a find and replace all and it should work. It did for me.

  5. This is a good script – but how do I limit the number of images it pull in. I only want to display 5.

    Thanks

  6. I was able to limit the number of images by adding:
    if (i == 8) return false;
    before the end of the $.each function. So, in this case, just after
    htmlString += ‘‘;

    It seems the count starts with 0, because i == 8 will produce 9 pictures.

  7. Thanks for introducing me to jQuery, using JSON and the Flickr API. I’m off, becoming a real web developer now..! =)

    Frederik, Amsterdam

  8. Nice script!

    It works if I copy your sourcecode prom the example. It’s showing your pictures perfectly.

    Though, when I put in my own API string it doesn’t work anymore. I used the rss-string from my phototream and replaced ‘rss_200′ with ‘json’.

    Now it just displays an empty square in my site.

    Besides that I’d like to ‘unrandomize’ the list and put the latest picture on top.

    Can you or someone help me with this?

    Thanks a lot!

    - Rick

  9. Hi, like your code and it’s working just fine.
    But can anyone tell me how to get more than 20 items in the feed? I have already figured out that it should be possible using a custom request with a flickr api-key.
    Would be very thankful for any hint or example.

  10. Same question as Chris:

    Hi, like your code and it’s working just fine.
    But can anyone tell me how to get more than 20 items in the feed? I have already figured out that it should be possible using a custom request with a flickr api-key.
    Would be very thankful for any hint or example.

  11. Hey just wanted to thank you for the exceptionally helpful post. I’ve been spending A LOT of time trying to get my mind wrapped around the flickr api and parsing json and this post helped to paint a clear picture.

    For those asking about how to display more than 20 photos… Have a look at this api fuction call: http://www.flickr.com/services/api/flickr.photos.getRecent.html

    You’ll want to create a URL like this: http://api.flickr.com/services/rest/?&method=flickr.photos.getRecent&api_key=yourAPIkeyhere&per_page=number of photos you want to display]&format=json

    Of course, that statement will only get a set number of your MOST RECENT photos.

  12. Hi, I’d just like to add that if you want more images, or more flexibility in terms of the feed, I’d highly recommend using the API with your own developer key. Check out the API Explorer that Flickr has to see how it works. I’m using the getPublicPhotos method and it can provide the url to the larger image, the description of a photo and a lot more. The feeds are basically just generalized versions of the same thing, and while easier to use, they just dont have the power to do everything. Once you play with the API a bit more, you’ll see what I mean. Cheers, and kudos again for the tutorial!

  13. I was having the same issue as ChequeredManiac. Then I realised that by changing “groups_pool.gne” to “photos_public.gne” for the images feed call I had it working.

    Thanks for sharing your work.

  14. Is it possible to cycle the 3×3 grid? I would like to ad something like:

    $(‘#images’).cycle({
    fx: ‘fade’,
    speed: ‘normal’,
    timeout: 7000,
    next: ‘#next’,
    prev: ‘#prev’
    });

    but cannot figure out how to incorporate it into your code. Thanks for the tutorial!

  15. Hello, I have implemented this correctly, just taking my feed, but it for some bizarre reason doesn’t return the first two photos. Would you know what causes this? I removed the random photo return as I needed it returned in order…

  16. Right, just to let you know I tried setting my iStart to -2, and it now works correctly, I do not know why I would need to do that… but all is well!

  17. Hi there,
    this one is exactely what i was looking for, an easy way to display photos from my flickr to my site.

    I’ve just a question. Is there a way to get photos from a user account instead of a group?

  18. a better solution for random

    function shuffle(sourceArray) {
    for (var n = 0; n < sourceArray.length – 1; n++) {
    var k = n + Math.floor(Math.random() * (sourceArray.length – n));

    var temp = sourceArray[k];
    sourceArray[k] = sourceArray[n];
    sourceArray[n] = temp;
    }
    }

    then just before your $.each

    shuffle(data.items);

  19. @Alex Thank you so much!!

    Note: When copying from the site, I had to replace the – signs as they didn’t copy correctly. Just in case anyone else wanted to use the solution provided.

  20. Thanks a bunch for your post, it helped a lot. Hate to be a standards nut, but I concatenated the ul tags so the list would be semantically correct.

    var htmlString = “”;

    // Now start cycling through our array of Flickr photo details
    $.each(data.items, function(i,item){

    // I only want the ickle square thumbnails
    var sourceSquare = (item.media.m).replace(“_m.jpg”, “_s.jpg”);

    // Here’s where we piece together the HTML
    htmlString += ‘‘;
    htmlString += ”;
    htmlString += ‘
    ‘;

    });

    htmlString += ”;

  21. why do tags not print here? doesn’t make too much sense for a forum about development….;-) (and no ‘edit’ option to re-write comment..)

    I meant:

    where is your ‘ul’ element into which you put the <li>’s???

    I hope it comes out right this time.. there’s no “preview” function either…;-)

    1. This code of yours works now. I did have to make a couple of very minor changes:

      $(document).ready(function() {

      // console.log(‘test’);
      // http://www.richardshepherd.com/how-to-use-jquery-with-a-json-flickr-feed-to-display-photos/
      // json: http://api.flickr.com/services/feeds/groups_pool.gne?id=998875@N22&lang=en-us&format=json&jsoncallback=?

      $.getJSON(“http://api.flickr.com/services/feeds/groups_pool.gne?id=998875@N22&lang=en-us&format=json&jsoncallback=?”, displayImages);

      function displayImages(data) {

      // Start putting together the HTML string
      var htmlString = “”;

      // Now start cycling through our array of Flickr photo details
      $.each(data.items, function(i,item){

      // I only want the ickle square thumbnails
      var sourceSquare = (item.media.m).replace(“_m.jpg”, “_s.jpg”);

      // Here’s where we piece together the HTML
      htmlString += ‘‘;
      htmlString += ”;
      htmlString += ‘
      ‘;

      });

      // Pop our HTML in the #images DIV
      $(‘ul’).html(htmlString);

      // Close down the JSON function call
      }
      });

      body {margin:100px; }

      json results here:

  22. Hi, thanks for a great tut! But I ran into some trouble.. I can’t seem to get the ID right. You know.. the part that I was suposed to switch your ID with mine. Don’t know whats wrong. I even started a new pool (public) and all, but it still wont work.

    Please help :)

    Cheers!

  23. Hello I am trying to load my albums (sets) in the drop down, but How I can display my pictures on the selected album? If I choose album2 from the dropdown list, it should display the pictures of album2.

    Here is the source code, I implemented…

    Learning Json

    Example of object creation in JSON in JavaScript

    $.getJSON(“http://api.flickr.com/services/rest/?method=flickr.photosets.getList&api_key=xxxxxyyyydddsssssslskhlh&user_id=xxxxyyyzzzzz&format=json&jsoncallback=?”, function (data) {
    var list = $(“”)
    $.each(data.photosets.photoset, function (i, set) {
    var link = $(““).attr(“title”, set.description._content)
    .attr(“href”, “http://www.flickr.com/photos/xxxxyyyyxzzzzz/sets/” + set.id)
    .text(set.title._content);
    var option = $(“”).append(link).append(” (” + set.photos + “)”);
    $(list).append(option);
    });
    $(“#flickr-sets”).append(list);

    });

    function displayImages(selectObject){
    alert(selectObject);
    //$.getJSON(“http://api.flickr.com/services/feeds/photos_public.gne?id=xxxyyaaa&lang=en-us&format=json&jsoncallback=?”, “”, abc);

    }

    function abc(data, textStatus, jqXHR){
    alert(data['title']);

    }

    Thanks,
    Krish

  24. requesturl=http://www.flickr.com/services/oauth/request_token?oauth_nonce=’+OAuth.nonce(6)+’&oauth_timestamp=’+OAuth.timestamp()+’&oauth_signature_method=HMAC-SHA1&oauth_signature=’+signature+’&oauth_consumer_key=’+consumerKey+’

    I’m trying to get token & token secret value from the given above url via $.ajax({
    type: “GET”,
    url: requesturl,
    dataType: ‘html’,
    success: callback,});
    but flickr response 401 unauthorized ..
    can you help me how to retreive the value of oauth token & secret?

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>