Monday, May 10, 2010

Twitter API with jQuery

After spending some time with Twitter REST API and jQuery; I decided to develop a small application to test both of these together. The example uses jQuery Ajax commands to load the given users public timeline through Twitter REST API.

jQuery is awesome and very popular JavaScript library which provides zillions of operations to manipulate client side objects. jQuery Ajax operations make it very easy to call the Twitter REST API and get the data in JSON format. The following line of code will call the Twitter for a user public timeline.

var url = "http://twitter.com/status/user_timeline/"+ $("input#tweepal").val()+".json?callback=?"; 
$.getJSON( url, function( data ){
   // process the reply  
});

For simplicity I have taken a textbox to enter the Twitter username with id "tweepal". The Twitter REST url contains a query string parameter "callback" without which Twitter reply will not be available to the Ajax function. Once received the data can be accessed like a normal JavaScript object. The received object is an array of tweets which can be easily traversed with jQuery.each() function.

$.each(data, function(n, tweet){
      $("div#tweet_time").val(tweet.created_at);
      $("div#tweet_text").val(tweet.text);
});

This completes all the blocks required to interact with Twitter from client side only. 


However there are plenty of libraries available for Twitter but its always exiting to make something on your own (specially using Twitter). Well I am struggling on how to post update using OAuth in same example. Will definitely post if get success.