Saturday, May 16, 2009

Using Twitter and Google Search API's using jQuery

Google and Twitter (API docs) both have API's available for web developers to create mashups using data from them. As a way to give users a broader view of what is happening around the constituency, state, party or representative they are viewing, GovCheck shows 4 searches on each of these pages - News, Web and Video search from Google and real time search from Twitter. These searches are all performed using the jQuery JavaScript framework. This has two advantages - the searches don't hold up page loading (as they happen asynchnously - AJAX :)) and they happen on the client side which means fewer resources (and hence load) used on the server side. So how exactly is this done?
The technology making this possible (besides the languages and TCP etc.) is JSONP. What this does is allow us to send AJAX requests to remote sites (due to security issues, browser do not allow cross domain AJAX requests. JSONP is a protocol that allows us to do so - although it has it's own issues too). Both Google as well as Twitter search support JSONP, as does jQuery - which makes querying those services from the client side very easy. Here's how to go about it.

function getGoogleContent(elem, searchtype, query) {
$.getJSON('http://ajax.googleapis.com/ajax/services/search/' + searchtype + '?v=1.0&q=' + query + '&callback=?',
function(data) {
if(data.responseData.results.length == 0)
elem.html($('

').html('No results').attr('style','text-align: center; font-weight: bold; font-size: 1.2em;'));
else {
elemliststr = elem.attr('id') + '-list';
elem.html($('
    ').attr('id',elemliststr).attr('style','list-style-type: disc; padding-left: 30px;'));
    elemlistobj = $('#' + elemliststr);
    $.each(data.responseData.results, function(i, item) {
    elemlistobj.append($('

  • ').html($('').html(item.title).attr('href', (searchtype == 'video') ? item.url : item.unescapedUrl).attr('target','_blank')).append((item.publisher) ? ' (' + item.publisher + ')' : ' '));
    });
    elem.append($('

    ').html($('').html('More Results').attr('href', data.responseData.cursor.moreResultsUrl).attr('target', '_blank')).attr('style', 'padding-top: 10px; font-weight: bold; text-align: center;'));
    }
    }
    );
    }

    function getTwitterContent(query) {
    elem = $('#twitter-tab');
    $.getJSON('http://search.twitter.com/search.json?q=' + query + '&rpp=4&callback=?',
    function(data) {
    if(data.results.length == 0)
    elem.html($('

    ').html('No results').attr('style','text-align: center; font-weight: bold; font-size: 1.2em;'));
    else {
    elemliststr = elem.attr('id') + '-list';
    elem.html($('
      ').attr('id',elemliststr).attr('style','list-style-type: disc; padding-left: 30px;'));
      elemlistobj = $('#' + elemliststr);
      $.each(data.results, function(i, item) {
      elemlistobj.append($('

    • ').html($('').html(item.from_user).attr('href', 'http://twitter.com/' + item.from_user).attr('target', '_blank')).append(': ' + item.text));
      });
      elem.append($('

      ').html($('').html('More Results').attr('href', 'http://search.twitter.com/search?q=' + query).attr('target', '_blank')).attr('style', 'padding-top: 10px; font-weight: bold; text-align: center;'));
      }
      }
      );
      }

      We use jQuery's getJSON call to get the JSON results from these services. The "&callback=?" at the end of both the JSON queries tells getJSON that these are JSONP requests - jQuery automagically substitutes the name of the function the results of the query should be fed to.
      The "elem" and "searchtype" arguments being sent to the "getGoogleContent" function allow me to call the same function for all News, Web and Video searches like so:

      getGoogleContent($('#news-tab'), 'news', query);
      getGoogleContent($('#youtube-tab'), 'video', query);
      getGoogleContent($('#web-tab'), 'web', query);

      Another thing to note here is the usefulness of FireBug. When I was starting out making these queries, I relied on console.log to see the returned object structure (since neither Google nor Twitter specify it) which then allowed me to make the right calls for the relevant data.

      So there you go - a quick, easy and scalable way of using Google and Twitter's API's to bring in information into your website.

      No comments: