Get Twitter Update With JQuery

From the previous article I wrote, Get Last Tweet Without OAuth Using PHP, I now want to share how to get the Twitter update with jQuery.

Getting Twitter updates with jQuery is not much different — we use the same API given by Twitter, process it, and display the results. You can get the Twitter update from someone using their username with this Twitter API:

http://api.twitter.com/1/statuses/user_timeline/username.format?callback=?

Where username would be the Twitter username, and format could be json, xml, atom, or rss.

Okay, as usual, if we want to use jQuery we need to include the jQuery library in our HTML file. As Google hosts it, we can get it for free from:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>

And then I created a form to get the username:

<form id="twitterForm">
<input type="text" value="ivankrisdotcom" size="30" id="username" name="username" />
<div id="button_block">
<input type="submit" id="submitButton" value="Get Tweets"/>
</div>
</form>
<div id="tweets"></div>

And now the jQuery part:

<script type="text/javascript">
$(document).ready(function(){
	$("#submitButton").click( function() {
		var username=$("#username").val();
		var format="json";
		var url='http://api.twitter.com/1/statuses/user_timeline/'+username+'.'+format+'?callback=?';
		if(username != ""){
			$.getJSON(url,function(tweets){ // get the tweets
				$.each(tweets, function(i, tweet){
					$("#tweets").append(tweet.text + "<br/>");
				});
			});
		}
		else{
			alert("Username cannot be empty");
		}
		return false;
	});
});
</script>

Code explanation: When submitButton is clicked, it gets the username from the username textbox, sets the format, and sets the URL to the Twitter API. Then it checks if the username is blank and shows a warning message if so. If the username is filled in, it gets the data from the Twitter API with a JSON call. Then the JSON result loops and each piece of JSON data is displayed in the browser.

Get Twitter update with jQuery demo page.