JQuery Templates and the Topsy Otter Twitter Search API

In a previous article I covered how to parse JSON API results to C# classes, using the Topsy Otter API as an example. In this article, we will examine the use of jQuery to make the remote call, returning the JSON result, and then display it in a table using the new jQuery Templating mechanism.

Here is a link to the previous article if you would like to read it first..

If you haven't looked into jQuery yet, I recommend that you do. In fact, Microsoft recently announced that with their new support for jQuery in Visual Studio, they will no longer be focusing on Microsoft AJAX, but jQuery instead. Microsoft has been a big contributor to the jQuery Template offering.

Probably the easiest way to present this is to show you all the markup and script first, and then I'll attempt to explain it:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
  <TITLE>Topsy Otter API Search With jQuery Template</TITLE>   
  <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
  <script type="text/javascript" src="http://ajax.microsoft.com/ajax/jquery.templates/beta1/jquery.tmpl.min.js"></script>  
  <script id="otterTemplate" type="text/x-jquery-tmpl">     
   <table cellspacing="2" cellpadding="2" border="0" width="50%" align="center" >              
               <tr style="background-color:#CCFFFF">
                 <td> <img src='${topsy_author_img}' width='75px' /></td> <td>Twitter Permalink: <a href='${trackback_permalink}'>Link</a></td>
  <tr style="background-color:#FFCCFF" ><td colspan="2">${content}</td></tr>
                   <tr style="background-color:#CCFF66"><td colspan="2">Url: <a href='${url}'>${title}</a></td></tr>                  

<script type="text/javascript">    

$(document).ready(function() {        
type: "GET",                  
url: "http://otter.topsy.com/search.json?q="+ $("#search").val() + "&perpage=100",                  
data: "{}",                    
contentType: "application/json; charset=utf-8",
dataType: "json",                
success: AjaxSucceeded,
error: AjaxFailed              

function AjaxSucceeded(result) {
function AjaxFailed(result) {         
$('#container').html(result.status + ' ' + result.statusText);

function BuildTable(msg) {
<div align="center">
  <h2>Topsy Otter API Search With jQuery Template</h2>
<input type="text" id=search /><input type="button" id=submit value="Search" />
<DIV id="container" />

As we look at the above page from top to bottom, here's what's happening:

1) Inside the <HEAD> tag, we load the required jQuery and jQuery template scripts from their respective CDN's:

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
  <script type="text/javascript" src="http://ajax.microsoft.com/ajax/jquery.templates/beta1/jquery.tmpl.min.js"></script>  

2) Underneath that, I have a jQuery Template which is defined inside script tags, with a type of "text/x-jquery-tmpl". What follows inside this script tag is simply an HTML table definition. The basic databinding syntax with jQuery Templates is ${ itemName }. It's that simple. There is a complete set of additional Template binding tags that you can examine at the jQuery site here.  Available template tags include: ${}, {{each}}, {{if}}, {{else}}, {{html}}, {tmpl}} and {{wrap}}.

3) the final script block defines the standard jQuery  $(document).ready(function() { ... that ensures that our event code doesn't fire until the entire document is loaded.

4) Inside this function I have a jQuery button click function for the "submit" button on the page:  $("#submit").click(function(event){

5) Finally, when the button is clicked, the jQuery $.ajax({ .... function is invoked. This performs a GET request to the Topsy Otter API endpoint with the value of the "search" textbox appended, and then "&perpage=100", which tells the Otter API that I want 100 results returned from the search.  The data{} parameter is empty as we are doing a GET, not a POST. the contentType and dataType are specified.

6) The last two parameters to the jQuery $.ajax function are the names of two callback functions, one for success, and the other for failure.

7) The AjaxSucceed function simply calls my BuildTable function, passing in a subset of the response object, "list". This contains the JSON to build my results table with.

8) BuildTable calls the .empty() function on the "container" div so that if we do another search, the results won't be appended to earlier results.

9) Finally, we do the actual databinding with $('#otterTemplate').tmpl(msg).appendTo('#container'); , which just says, "using the otterTemplate, take the msg object, bind the specified fields, and then append the results to the "container" DIV on the page.

This is elegant, compact code. It's easy to learn, and it all happens on the client - in the browser.  You can try out the actual page here.  

NOTE: Some corporate firewalls, in their infinite wisdom, will block the ajax call. Don't blame me!

Just View Source to see the code, or you can choose File / Save As / Web Page (HTML Only) and play with it to your heart's content. Have fun with jQuery and jQuery Templates!

By Peter Bromberg   Popularity  (2542 Views)