Monday, May 28, 2012

jQuery Tutorial: Integrating with Flickr's JSON API

Overview:
This will be another article on jQuery. Here, we'll be mainly focusing on how jQuery eases the usage of the Ajax API for JSON.

You may also refer to the first jQuery article "jQuery Tutorial: Ajax Processing - GET and POST".

The sample code for this article can be found here.

Application Demo:
The application displays images from Flickr.com that are tagged by the input provided by the user.

Home page:


Displaying the Result:



Project Structure:

 org.fazlan.jquery.flickr.app  
 |-- pom.xml  
 `-- src  
   `-- main  
     |-- resources  
     `-- webapp  
       |-- img  
       |  `-- ajax-loader.gif  
       |-- index.jsp  
       |-- jquery.js  
       `-- WEB-INF  
         `-- web.xml  

Step 1: Creating a the Web Project.

 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
      xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">  
   <modelVersion>4.0.0</modelVersion>  
   <groupId>org.fazlan</groupId>  
   <artifactId>org.fazlan.jquery.flickr.app</artifactId>  
   <packaging>war</packaging>  
   <version>1.0.0-SNAPSHOT</version>  
   <name>org.fazlan.jquery.flickr.app Maven Webapp</name>  
   <url>http://maven.apache.org</url>  
   <dependencies>  
     <dependency>  
       <groupId>junit</groupId>  
       <artifactId>junit</artifactId>  
       <version>3.8.1</version>  
       <scope>test</scope>  
     </dependency>  
   </dependencies>  
   <build>  
     <finalName>jquery.flickr.app</finalName>  
     <plugins>  
       <plugin>  
         <groupId>org.mortbay.jetty</groupId>  
         <artifactId>maven-jetty-plugin</artifactId>  
         <version>6.1.10</version>  
       </plugin>  
       <plugin>  
         <groupId>org.apache.maven.plugins</groupId>  
         <artifactId>maven-compiler-plugin</artifactId>  
         <version>2.4</version>  
         <configuration>  
           <source>1.6</source>  
           <target>1.6</target>  
         </configuration>  
       </plugin>  
     </plugins>  
   </build>  
 </project>  

Step 2: Verifying the Flickr Endpoint

Click on the following link, this will generate a JSON output from Flickr.com.

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


Step 3: Defining the JSP


index.jsp
 <html>  
 <head>  
   <title>Flicker Image Library</title>  
   <script type="text/javascript" src="jquery.js"></script>  
   <script type="text/javascript">  
     // jQuery document ready
  
     $(function() {  
 /*  
            $("#tagDiv").ajaxStart(function(){  
             $('#loadImg').show();   
          });  
            $("#tagDiv").ajaxComplete(function(){  
             $('#loadImg').hide();   
          });  
 */  

       // when hit Enter on the text field  
       $('#tagField').keypress( function(evnt) {  
             var code = (evnt.keyCode ? evnt.keyCode : e.which);  
           // code to trap 'Enter' key  
           if( code == 13 ) {  
             getFlickrImages();  
           }  
       });  

       // when clicked on search button  
       $('#exploreBtn').click(function() {  
         getFlickrImages();  
       });  
     });  

     function getFlickrImages() {  
      var data = 'tags=' + $('#tagField').val().trim() + '&tagmode=any&format=json&jsoncallback=?';  
      $('#loadImg').show();  

     // sending a AJAX call to the flickr and expect JSON as return type  
      $.ajax({  
        type: 'GET',  
        url: 'http://api.flickr.com/services/feeds/photos_public.gne',  
        data: data,  
        dataType: 'json',  
        error: function(xhr, status, error) {  
             alert(status + '--> ' + error);  
           },  
        success: function(data) {  
             $('#loadImg').hide();                    
             $('#contentDiv').html(data.title);  
             $('#resultDiv').html('<center><table id="imageTable" style="border: 1px solid black; text-align:center"><tr></tr></table></center>');  
             $.each(data.items, function(index, item) {  
              // show FIVE images per row  
              if( index%5 == 0 ) {  
                   $('#imageTable tr:last').after('<tr></tr>')  
              }   
              //$('#imageTable tr:last').append('<td><img src=' + item.media.m + '></td>');    
              $('#imageTable tr:last').append('<td>' + item.description + '</td>');                           
             });  
         }  
      });  
     }  
   </script>  
 </head>  
 <body>  
 <h1 style="color: blue">Flicker Image Library</h1>  
 <div style="border: 1px solid blue" id="tagDiv">  
   <table style="color: blue">  
     <tr valign="middle">  
       <td><b>Tag Name</b></td>  
        <td><input type="text" id="tagField"/></td>  
       <td><button id="exploreBtn">Explore</button></td>  
       <td><img src="img/ajax-loader.gif" id="loadImg" style="display: none"/></td>  
     </tr>      
   </table>  
 </div>  
 <br>  
 <div id="contentDiv" style="border: 1px solid blue; color: blue"></div>  
 <div id="resultDiv"></div>  
 </body>  
 </html>  


The above Ajax call gives you more control over how you need to make the Ajax call. Conversely, you could also try the following:


var data = 'tags=' + $('#tagField').val().trim() + '&tagmode=any&format=json&jsoncallback=?';  

$.getJSON('http://api.flickr.com/services/feeds/photos_public.gne',  
      data,  
      function(result) {  
        $('#loadImg').hide();                    
        $('#contentDiv').html(result.title);  
        $('#resultDiv').html('<center><table id="imageTable" style="border: 1px solid black; text-align:center"><tr></tr></table></center>');  
        $.each(result.items, function(index, item) {  
         // show FIVE images per row  
         if( index%5 == 0 ) {  
             $('#imageTable tr:last').after('<tr></tr>')  
         }   
         //$('#imageTable tr:last').append('<td><img src=' + item.media.m + '></td>');    
         $('#imageTable tr:last').append('<td>' + item.description + '</td>');                           
        });  
 });  
Step 4: Building and Deploying the Application

$ mvn clean install
$ mvn jetty:run

mvn:jetty:run - would run the web app on the jetty server.

Now, you can access the application with the following URL.
http://localhost:8080/org.fazlan.jquery.flickr.app

Summary:
This article looked at how jQuery can be used to easily manipulate Javascript and simplify the usage of Ajax API for JSON.

The sample code for this article can be found here.

No comments:

Post a Comment