Tip of the day: Flickr + jQuery

Post date: 18-Mar-2012 01:25:16

While helping out a local business with their Flickr integration, I hit some gotchas regarding JSON and the Flickr API, so I thought I'd put up my code for anyone in a similar situation.

The main issue was Javascript origin policy - because I was collecting the data from Flickr's servers jQuery's normal getJSON mechanism won't work - you need to break out the 'jsonp' mechanism, and that means digging down to the 'ajax' method.

The other useful thing to know is that Flickr's default JSONP callback is called 'jsonFlickrApi', so make sure to drop that in the parameters for the ajax call.

Here's the example I used for testing. (Replace the api_key with your own - get one from Flickr's developer site.)

<html>
  <head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
    
    <script>
      $(document).ready(function() {     
        var api_key = '<api_key>';
        var user_id = "75427932%40N05";
        $.ajax({
          url: "http://api.flickr.com/services/rest/?method=flickr.photosets.getList&api_key=" + api_key + "&user_id="+user_id+"&format=json&callback=?", 
          dataType: 'jsonp',
          jsonpCallback: 'jsonFlickrApi',
          success: function(data) {
            if (data.stat == 'ok') {
              $(data.photosets.photoset).each(function(i, photoset) {
                var thumb_url = "http://farm"+photoset.farm+".staticflickr.com/"+photoset.server+"/"+photoset.primary+"_"+photoset.secret+"_t.jpg";
                var photoset_link = "http://www.flickr.com/photos/"+user_id+"/sets/"+photoset.id+"";
                var el = $(document.createElement('a')).attr('href', photoset_link).append($(document.createElement('img')).attr('src', thumb_url));
                el.append($(document.createElement('em')).html(photoset.title._content));
                $('#thumbs').append(el);
              });
            }
          }
        });  
      });
    </script>
    
    <style>
      #thumbs a {
        display: block;
        float: left;
        margin-right: 20px;
        width: 80px;
      }
      #thumbs img {
        border: 1px solid gray;
        padding: 1px;
      }
      #thumbs em {
        display: block;
        text-align: center;
      }
    </style>
  </head>
  
  
  <body>
    <div id="thumbs"></div>
  </body>
</html>