Creating a live Twitter status update with YQL and JavaScript
Final Result Preview
Let’s take a look at the final result we will be working towards:
Introduction
All major web sites these days offer an API to give developers access to their service. While there are some standards in place (like OpenSocial, OAuth etc) for the most part each web site exposes their service in their own unique way. This is a major headache for developers, who have to learn a new set of classes and functions for every site they work with.
YQL attempts to solve this issue by exposing a number of 3rd party web services through a single interface, with access provided through a very SQL like syntax. This means that getting a photo from Flickr, reading a status update on Twitter and searching Craigslist can all be done with the same syntax from the same service. This saves time that would be spent learning different APIs, reduces code footprint (because you aren’t including several different JavaScript libraries) and reduces the amount of code you have to write.
YQL is accessed by a REST web interface, returning either JSON or XML. In this tutorial we will look at accessing YQL from JavaScript to create a script that dynamically displays a Twitter status update.
Step 1 – Creating the YQL query
Before we start writing any code, lets take a look at how we use the YQL service.
The syntax used to access the YQL service is very similar to SQL. The YQL Console is a tool that lets you craft and test these queries before committing them to your code.
Open up the YQL Console in your browser. The Data Tables panel, in the bottom right hand corner, shows all the tables that YQL can access. Expand the twitter item and click on the twitter.user.status link. If the twitter item is not available, click the Show Community Tables link.
Almost all YQL tables include a sample YQL query. In this case we get the query select * from twitter.user.status where id=’bartt’. Anyone familiar with SQL should instantly recognize the format of the query.
The YQL Console provide two other important functions. The first is that it provides the URL that needs to be called, complete with all the required parameters, to execute the query from our code.
The second is a tree view of the object that is returned from that query. This lets us know how to access the properties from JavaScript.
This application will actually make use of the twitter.user.timeline table. This is because the twitter.user.status table does not include the twitter users profile image. The link for the twitter.user.timeline table in the YQL Console does not have a sample query, instead returning the default query desc twitter.user.timeline, which returns the details of the table itself rather than running a query on the data the tables holds. However we can query the twitter.user.timeline table just like the twitter.user.status table with select * from twitter.user.timeline where id=’mcasperson’.
Step 2 – Create a basic HTML document
With the YQL URL in hand, we now need to write some code. To demonstrate this application we first need a simple HTML file. The code below shows the outline of the HTML document.
Step 3 – Add a link to jQuery
For convenience we will use the jQuery library, which allows us to easily modify the HTML elements, as well as call the YQL service. You can get a copy of jQuery for yourself here. The following code, added in the tag, includes the jQuery code in our page.
Step 4 – Update the page when it is first displayed
A common problem in JavaScript occurs when you want to process the page when it is first loaded. The window.onload event is typically used to perform this initial processing, but this event is called before all the HTML elements are ready, meaning JavaScript that references specific elemets in the HTML DOM will fail. Fortunately jQuery provides a convenient way to execute JavaScript once the HTML DOM is initialized through $ (document).ready. Here we set the queryYQL function to be called once the document is ready.
$ (document).ready(queryYQL);
Step 4 – Calling the YQL service
The queryYQL function is where we actually call the YQL service and then display the results. In step 1 we obtained a copy of the URL that will query a users twitter status from YQL. You could copy that straight into your code without any problem (as long as you set the callback function to ? instead of the default cbfunc – this will be explained below). However, for this application we want to be able to specify whose Twitter account we will query. To achieve this we build up the final URL in a number of steps.
function queryYQL()
{
var yqlUrl = “http://query.yahooapis.com/v1/public/yql”;
The yqlUrl variable holds the base URL for the YQL service.
var query = “select * from twitter.user.timeline where id=’” +
document.getElementById(‘twittername’).value + “‘”;
We then build up the YQL query, obtaining the user name from a HTML input element (which will be added in later steps).
var queryUrl = yqlUrl + “?q=” + escape(query) + “&format=json&callback=?” + “&env=” + escape(“store://datatables.org/alltableswithkeys”);
Finally we combine the base URL, the YQL query (which has been encoded with the escape function), and the additional paramaters like format (set to JSON so we can use the returned data directly from JavaScript), callback (set to a question mark for jQuery), and evn (the value of which was copied from the URL supplied by the YQL Console) into the final URL.
The reason why the callback function is specified as a question mark is because jQuery will replace the question mark with a reference to the function passed into the getJSON function as the second parameter. You can find out more information the getJSON function here.
$ (“#twitterstatus”).text(“Loading Twitter Status…”);
$ (“#twitterimage”).css(“visibility”, “hidden”);
Before we contact the YQL servers, we first hide the image and display the message “Loading Twitter Status…”.
$ .getJSON(queryUrl, function (yqlObject)
This URL is then passed to the jQuery getJSON function, which will contact the YQL server and pass the JSON object that has been returned to a function supplied as the second parameter.
{
var twitterText = yqlObject.query.results.entry[0].title.replace(
document.getElementById(‘twittername’).value + “: “, “”);
$ (“#twitterstatus”).text(twitterText);
$ (“#twitterimage”).attr(“src”, yqlObject.query.results.entry[0].link[1].href);
$ (“#twitterimage”).css(“visibility”, “visible”);
}
);
The status updates are all prefixed with the twitter user name, like “mcasperson: this is my twitter status”. This leading user name is redundant (or at least better displayed elsewhere), so we use the string replace function to get a copy of the latest twitter status post where the user name has been removed.
To display the twitter status we update the element with an ID of twitterstatus with the last status update, and update an IMG element with the ID of twitterimage with the twitter users profile picture. We also set the
Incoming search terms for the article:
twitter update javascript (1)Pages: 1 2
tags: creating, JavaScript, live, Status, Twitter, Update