Saturday, 24 July 2010

Using jQuery and JSONP to load Twitter statuses

In this post I wanted to quickly share how to use jQuery to use Twitter's API to load tweets into a HTML page. This uses AJAX but importantly, it doesn't use any server side code like PHP to load the tweets. All the processing is done on the client's browser which communicates directly with the twitter server. This is possible because Twitter's API supports JSONP, an extension to JSON.

Wikipedia has a good discussion of JSONP but basically, it allows a page to request data from a server other than the one that originally served the page; this isn't usually allowed because of the 'same origin policy' that states that a dynamic element within a browser, such as JavaScript or Flash, can only communicate back to the server that it was loaded from. JSONP gets around this by injecting the JavaScript request into a script tag.

The following code loads my latest tweets into the page. Notice the call to jQuery's getJSON() method, and in particular the first argument. This is the address of the Twitter API for loading my tweets. If you want to load your own tweets, obviously swap 'lampmichael' for your own twitter handle. Also notice 'callback=?' at the end. This is the magic sauce. jQuery will replace the question mark with a dynamically generated function name and when the Twitter service responds to this request, it will call that function which in turn calls the anonymous function that is passed as the second argument to getJSON().

In the anonymous function, the tweets are simply dumped into the body tag within an unordered list. Each tweet has quite a lot of data. In the sample code I've left a commented out debugger statement. Remove the two slashes and load the page in Firefox with Firebug installed to see exactly what Twitter sends back.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "">
 <html xmlns="" xml:lang="en-gb" lang="en-gb" dir="ltr" > 
 <meta http-equiv="content-type" content="text/html; charset=utf-8" />
  <title>Twitter JSONP</title>
  <script src="" type="text/javascript"></script>
  <script type="text/javascript"><!--
  $(document).ready(function () {
      function(data) {
        if (data.length>0) {
          $('body').html('<ol id="tweets"></ol>');
          data.forEach(function(datum) {
            $('#tweets').append('<li>'+datum.text+' ('+datum.source+')</li>');
  <style type="text/css">
  #tweets {
    max-width: 400px;
  #tweets li {
 margin-bottom: 10px;
 padding: 2px
  #tweets li:nth-child(odd) {

As this is just HTML and JavaScript, save the code into a plain old HTML file and load it in your browser right off your desktop; there's no need to serve it from IIS or Apache.

No comments:

Post a Comment