Creating a Twitter Widget with Ajax
- What Is Twitter?
- Constructing the Twitter Widget
- Designing the Twitter Widget
What Is Twitter?
Essentially an Internet micro-blogging service (similar to Plurk, Jaiku, and Tumblr), Twitter is a social-networking phenomenon, growing into a must-have system for building online relationships for individuals and businesses alike. The London Telegraph reports that over a 12-month period Twitter use soared by 631%!
It's becoming increasingly popular for individuals and business that use Twitter to share their Twitter messages with the world. With "Follow me on Twitter" icons proudly displayed on many home pages, Twitter users are gaining exposure and ultimately making more connections. Some sites even display their latest twitters/tweets/tweatschoose your favorite terminology for "Twitter messages"with a link back to their Twitter account. In this article, I'll show you how to use Ajax to create a simple Twitter widget to display your own Twitter messages.
Let's get started with a simple overview of the pattern used to access the feed, and then we'll move on to the location where the request for the Twitter RSS feed begins.
Accessing a Twitter Feed with Ajax and PHP
The process of retrieving the Twitter RSS feed seems elaborate, because many different file types and languages are involved; however, the files contain very little code. The pattern for accessing the Twitter feed starts with an HTML file that contains this information:
- Reference to a JavaScript file
- URL of the RSS feed that will be requested
- Location where the widget will ultimately be displayed on the page
The JavaScript file contains a JavaScript object that makes an Ajax request to a PHP file. The PHP file is used to create a bridge between the JavaScript file and an external website, which in this case is the Twitter home page.
Embedding the Twitter Widget
As mentioned, the process of retrieving an RSS feed from Twitter starts with a basic HTML file. This file, called index.html, is shown in Listing 1.
The HTML code in index.html simply embeds a JavaScript file (Tweeter.js) and defines a few properties for the enclosed JavaScript object (Tweeter). Notice that the JavaScript file is embedded before the Tweeter object's properties are set; obviously, we need to ensure that the Tweeter object has been created prior to setting its properties.
Listing 1Embedding the Ajax Twitter widget (index.html).
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Creating a twitter widget with Ajax</title> <link href="css/tweeter.css" rel="stylesheet" type="text/css" /> </head> <body> <script type="text/javascript" src="js/Tweeter.js"></script> <script type="text/javascript"> <!-- Tweeter.url='http://twitter.com/statuses/user_timeline/16360132.rss'; Tweeter.tweetCount = 3; // Optional Tweeter.title = "Distant Measures latest tweets"; // Optional //--> </script> </body> </html>
In the sample code, you'll notice three properties being set:
- Tweeter.url
- Tweeter.tweetCount
- Tweeter.title
Tweeter.url is the only required property, as it supplies the URL to the Twitter feed that will be used in the widget; in this case, the URL is for the Distant Measures Twitter feed. The Tweeter.tweetCount and Tweeter.title properties are optional and have predefined values in the Tweeter.js file. To use your own Twitter feed URL, simply copy it from the right-hand column of your Twitter profile page.
Making the Ajax Request for the Twitter Feed
To ensure that the HTML file is loaded before attempting to add the widget to the page, the Tweeter object waits for the onload event and then fires Tweeter.Initialize (see Listing 2). The Tweeter.Initialize method is used to locate the enclosing script tags for the Tweeter.js file and insert the widget into the correct location, which is the location of the script tags in the HTML file. This design provides ultimate flexibility in the placement of the script, allowing us to drop the script anywhere we choose in an HTML page. Once the location of the enclosing script tag is discovered, the Tweeter.location property is set (for future reference in determining where to display the widget), and Tweeter.Request is fired. The Tweeter.Request method is where the magic happens, making an Ajax request to the gateway.php script (I'll discuss that shortly), with the Tweeter.url property as a query parameter.
Listing 2Requesting the Twitter feed and creating the widget (Tweeter.js).
var Tweeter = new Object(); Tweeter.title = "My Latest Tweets"; Tweeter.tweetCount = 2; Tweeter.links = new Array(); Tweeter.titles = new Array(); Tweeter.descriptions = new Array(); Tweeter.dates = new Array(); Tweeter.location = null; Tweeter.Initialize = function() { var scripts = document.getElementsByTagName('script'); for(var i=0; i<scripts.length; i++) { if(scripts[i].src.indexOf("Tweeter.js") != -1) { Tweeter.location = scripts[i]; Tweeter.Request(); break; } } } Tweeter.Request = function() { var gateway = 'service/gateway.php?feed='+escape(this.url); this.request = (window.XMLHttpRequest) ? new XMLHttpRequest(): new ActiveXObject("Microsoft.XMLHTTP"); this.request.onreadystatechange = function() { Tweeter.checkReadyState(); }; this.request.open('GET', gateway, true); this.request.send(gateway); } Tweeter.onResponse = function(feed) { var items = feed.getElementsByTagName('item'); for(var i=0; i<items.length; i++) { this.links.push(items[i].getElementsByTagName('link')[0].firstChild.nodeValue); this.titles.push(items[i].getElementsByTagName('title')[0].firstChild.nodeValue); this.descriptions.push(items[i].getElementsByTagName('description')[0].firstChild.nodeValue); this.dates.push(items[i].getElementsByTagName('pubDate')[0].firstChild.nodeValue); } var ul = document.createElement('ul'); ul.id = 'tweetWidget'; var title = document.createElement('li'); title.className = 'tweetTitle'; title.appendChild(document.createTextNode(this.title)); ul.appendChild(title); for(var i=0; i<this.tweetCount; i++) { var li = document.createElement('li'); var link = document.createElement('a'); link.appendChild(document.createTextNode(this.descriptions[i])); link.setAttribute('href', this.links[i]); li.appendChild(link); ul.appendChild(li); } this.location.parentNode.insertBefore(ul, this.location.nextSibling); } Tweeter.checkReadyState = function() { switch(this.request.readyState) { case 1: break; case 2: break; case 3: break; case 4: this.onResponse(this.request.responseXML.documentElement); } } window.onload = function() { Tweeter.Initialize(); }
Making an External Ajax Request
After the request is made, the gateway.php script (shown in Listing 3) bridges the gap between the Tweeter object and the external Twitter feed. For security reasons, Ajax cannot make remote/external calls to XML; therefore, gateway.php accesses the Twitter feed specified in the query string and returns the XML locally.
Listing 3Bridging the gap between Ajax and the Twitter RSS feed (gateway.php).
<?php header("Content-Type: application/xml; charset=UTF-8"); $feed = (isset($_REQUEST['feed'])) ? $_REQUEST['feed'] : ''; if(!empty($feed) || is_string($feed)) echo file_get_contents($feed); ?>