This post is an update from the old post. A lot of things changed since it was written and the information in the old one is a bit outdated.

First of all, you should never use an eval() when using JSON because of security reasons that I will talk about later in another post. [edit : jQuery uses eval() but there's a work-around that will be talked about in another post.]

JSON and jQuery

The simplest way to use JSON is though jQuery. I have been using for more than 2 years and I never was disappointed.

Let's say I want to call Flickr search with JSON. It's simple :

      { method : "",
          api_key : "4ef2fe2affcdd6e13218f5ddd0e2500d",
          format : "json",
          tags : "landscape",

The $.getJSON takes 3 parameters.

1. The URL The URL of the remote call.

2. The parameters The parameters to complete the call. On the documentation page about this Flickr method, you have a list of all the parameters you can use. For a JSON call on Flickr, you have to send the api_key and the format. I added the parameter tags to send me all photos that are tagged landscape.

3. The callback Most API services now requires a callback, a method that will be called when the JSON is loaded. It is more secure and easier to work with. At the end of the first parameter (the URL), I added jsoncallback=? (flickr called this parameter jsoncallback but it could be named differently on other services). This is the jQuery-way of saying “When you finish loading the JSON, call the method specificied by the third argument”.

You may wonder how Flickr knows which function to use on callback. It's because in jQuery, there's a special case for that. In the URL, you can see that the jsoncallback is written like that jsoncallback=?. The ? is replaced by your own callback method (in my case, I called it ajaxCallback)

The callback method

The callback method I used looks like this :

function ajaxCallBack(data) {
      // Loop throught all photos and display them
      // it uses the jquery.each method 
      // doc at
      $.each(, function(photoIdx, photo) {
          // Build the thumbnail url
          var thumb_url = ["http://farm",, "", 
              photo.server, "/",, "_", photo.secret, "_t.jpg"].join("");
          // Build the photo url
          var photo_url = ["", 
              photo.owner, "/",].join("")
          // Build HTML
                  .attr("href", photo_url)
                  .attr("target", "_blank")
                      $("").attr("src", thumb_url)

If you know jQuery a little, it simply creates the HTML to show the thumbnails and a link to the photo.

Get the code

You can get the complete code for this example on GitHub and a working example.

comments powered by Disqus