Using Flickr and jQuery to learn JSONP
Feb 5 2010I was playing around with the Flickr API recently and got a little stuck: when using jQuery to call the Flickr public feed using jQuery’s $.getJSON method, I wasn’t getting any results. I thought maybe I was parsing the response incorrectly, but when I went to check out the data coming back in firebug, nothing was there. I couldn’t believe it- the response headers were present, but the body was blank. Calling the public feed url from the browser worked fine. What’s more interesting was everything worked in IE. So I did some experimenting and learned the issue: I wasn’t correctly using the endpoint to work with JSONP, which is required when using jQuery with Flickr. Then I thought I better learn more about JSONP.
There are plenty of good articles about JSONP on the net. Essentially, JSONP allows you to specify custom callbacks when making remote ajax calls. Firefox seems to be more strict when dealing with jsonp, which is why I didn’t get a response body. What did the trick was adding the
jsoncallback=?
query string parameter to the end of my Flickr url. This allows the jQuery framework to route to the default success function you pass to .getJSON(), like so:
$.getJSON( 'http://api.flickr.com/services/feeds/photos_public.gne?format=json&jsoncallback=?', function(data) { $.each(data.items, function(i, item) { $("img").attr("src", item.media.m).appendTo("#images"); }); });
Here’s an example of this call. So what happens if we replace the ? with something else? Well, passing a simple text string will be treated like a normal function call. Take a look at the example below:
function GetItemsUsingExternalCallback() { $.ajax({ url: 'http://api.flickr.com/services/feeds/photos_public.gne?format=json&jsoncallback=myCallbackFunction', dataType: 'jsonp' }); } function myCallbackFunction(data) { //dostuff }
jQuery will try and call “myCallbackFunction” as a normal function call instead of routing to the standard success function that’s part of the getJSON call. The example page also includes this approach. There’s only a slight difference between the two approaches, but it’s cool that jQuery can call a function outside of the normal success callback. Of course, if you needed to reuse a common callback across multiple ajax calls, you’d probably want to call that function directly from the success method, rather than inlining the function in the .ajax call.