Bali Web Design Studio is a small enthusiast web design studio based in Bali, Jakarta, Indonesia.

Twitter API + jQuery JSONP

Here i will show you how easily fetch non authenticated Twitter API methods using ajax json callback functions with jQuery framework, I use user_timeline method as an example but you can use this sampel to fire other twitter api method as long as its needless authorization.

The TwitterAPI Class

TwitterAPI = {
	Statuses: {
		user_timeline:function(screen_name, count, callback){
			jQuery.getJSON("http://twitter.com/statuses/user_timeline/" + screen_name + ".json?count="+count+"&b="+Math.random()+"&callback=?", 
			callback);
		}
	}
};


Why do i used nested objects? twitter classified their API methods and I personally think that its good to follow the Twitter API structures, it will help you easily spoting the methods and online documentation of each methods wherever needed. The code above create a javascript object named “TwitterAPI” which has class member ( an object ) “Statuses” which has methods user_timeline with some parameters:

  1. screen_name: (string) your twitter username
  2. count: (int) count of statuses that you need to fetch
  3. callback: (function) javascript function that will fired when the json result is coming

for more references about this methods parameters have a look at Twitter API Wiki

Implementation

Create the HTML DOM container element in your body/sidebar when you need the list of statuses to be appeared (eg. ID: HTML5:aside)

<aside></aside>

Load jquery framework

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>

Put the code that we made above (API Class & Use Method Function) after jQuery load, you can either put it between or before the closing tag. Next you need to fire the API method on DOM ready with parameters as discribes above.

jQuery(document).ready(function($){
TwitterAPI.Statuses.user_timeline("chazzuka",5,function(json){
	var content = '<ul>';
	$.each(json, function(i){
		var tweet = this['text'];
		var d = new Date(this['created_at']);
		var date_show = d.getDate()+'/'+d.getMonth()+'/'+d.getFullYear()+' '+d.getHours()+':'+d.getMinutes();
		content += '<li>' + tweet + ' (<date>'+date_show+'</date>)</li>';
	});
	content += '</ul>';
	$('aside').append(content);
});
});

Adjustment

If you follow the steps above now you will have the plain text list of your tweets, now we need to convert “mentions (@)”, “hash (#) tags” and “valid url format” into clickable links, for this purpose I taken the function below from Remy Sharp code (based on dustin diaz code).

window.ify=function(){var entities={'"':'&quote;','&':'&amp;','<':'&lt;','>':'&gt;'};return{"link":function(t){return t.replace(/[a-z]+:\/\/[a-z0-9-_]+\.[a-z0-9-_:~%&amp;\?\/.=]+[^:\.,\)\s*$]/ig,function(m){return'<a href="'+m+'">'+((m.length>25)?m.substr(0,24)+'...':m)+'</a>';});},"at":function(t){return t.replace(/(^|[^\w]+)\@([a-zA-Z0-9_]{1,15})/g,function(m,m1,m2){return m1+'@<a href="http://twitter.com/'+m2+'">'+m2+'</a>';});},"hash":function(t){return t.replace(/(^|[^\w'"]+)\#([a-zA-Z0-9_]+)/g,function(m,m1,m2){return m1+'#<a href="http://search.twitter.com/search?q=%23'+m2+'">'+m2+'</a>';});},"clean":function(tweet){return this.hash(this.at(this.link(tweet)));}};}();

just copy the code into your HTML document and we need to change the callback functions as follow:

jQuery(document).ready(function($){
	TwitterAPI.Statuses.user_timeline("chazzuka",5,function(json){
		content = '<ul>';
		$.each(json, function(i){
			var tweet = ify.clean(this['text']);
			var d = new Date(this['created_at']);
			var date_show = d.getDate()+'/'+d.getMonth()+'/'+d.getFullYear()+' '+d.getHours()+':'+d.getMinutes();
			content += '<li>' + tweet + ' (<date>'+date_show+'</date>)</li>';
		});
		content += '</ul>';
		$('aside').append(content);
	});
});

Thats it, now you have your own widget.

Notes:

Theres limitation about the amount of request per hour, so if your pages is a high traffic page then you may need to use caching mechanism otherwise you will get error limit request exceeded from Twitter API.

Final Code

<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>JQuery JSONP + Twitter API</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
TwitterAPI = {
	Statuses: {
		user_timeline:function(screen_name, count, callback){
			jQuery.getJSON("http://twitter.com/statuses/user_timeline/" + screen_name + ".json?count="+count+"&b="+Math.random()+"&callback=?", 
			callback);
		}
	}
};
// @rem
window.ify=function(){var entities={'"':'&quote;','&':'&amp;','<':'&lt;','>':'&gt;'};return{"link":function(t){return t.replace(/[a-z]+:\/\/[a-z0-9-_]+\.[a-z0-9-_:~%&amp;\?\/.=]+[^:\.,\)\s*$]/ig,function(m){return'<a href="'+m+'">'+((m.length>25)?m.substr(0,24)+'...':m)+'</a>';});},"at":function(t){return t.replace(/(^|[^\w]+)\@([a-zA-Z0-9_]{1,15})/g,function(m,m1,m2){return m1+'@<a href="http://twitter.com/'+m2+'">'+m2+'</a>';});},"hash":function(t){return t.replace(/(^|[^\w'"]+)\#([a-zA-Z0-9_]+)/g,function(m,m1,m2){return m1+'#<a href="http://search.twitter.com/search?q=%23'+m2+'">'+m2+'</a>';});},"clean":function(tweet){return this.hash(this.at(this.link(tweet)));}};}();
</script>
</head>
<body>
<aside>
<h3>My Tweets</h3>
</aside>
<script type="text/javascript">
jQuery(document).ready(function($){
TwitterAPI.Statuses.user_timeline("chazzuka",5,function(json){
	content = '<ul>';
	$.each(json, function(i){
		var tweet = ify.clean(this['text']);
		var d = new Date(this['created_at']);
		var date_show = d.getDate()+'/'+d.getMonth()+'/'+d.getFullYear()+' '+d.getHours()+':'+d.getMinutes();
		content += '<li>' + tweet + ' (<date>'+date_show+'</date>)</li>';
	});
	content += '</ul>';
	$('aside').append(content);
	});
});
</script>
</body>
</html>

8 Responses.

  1. Blain Smith May 12, 2011

    Very nice, thank you. I tweaked it a bit since getMinutes() only returns single digits if its less than 10.

    A little shorhand fix:

    ((time.getMinutes() < 10) ? '0'+time.getMinutes() : time.getMinutes())

  2. Mike March 18, 2011

    Thanks for the code. However after putting it on my page, it shows the date incorrectly – one month older – what could be the problem? THX

  3. Idek March 7, 2011

    Thanks bro.. it’s so nice.. :)

  4. Green Industry January 30, 2011

    WOW!! Its very coll and informative i Love it and its i think work..
    Thank you for post..

  5. Php2ranjan October 19, 2010

    wow, I think it is really gonna work. thanks for the code

  6. Christof Coetzee October 8, 2010

    very nice jquery ajax tutorial – thanks, I’m busy trying it out now and will let you know of any bugs.

  7. ben joven October 6, 2010

    cool stuff…finished application? I’m doing the same thing with JSON and certain search terms.

Leave a Reply

bali web design studio Freelance Web Developer Works Bali Web Design Portfolio Get Web Design Quotation RSS Feeds