Fetch twitter feed with JavaScript

Who said you can’t fetch data across domains?

In this blog I show you how to include a twitter feed on you web-page which fetches data from twitter in plain JavaScript, directly from the client’s browser to twitter.com.

Same origin you said?

We all know that “ajax” call’s in JavaScript must follow the same origin policy. This usually leads to using a proxy one the same domain to proxy ajax-calls to the external services. This leads to more work for your server and more code for you to write. Who invented this same origin stuff anyway?

Of course it is supposed to be more secure? for the end user, but is it actually? If we end up proxy all the calls? Is it then more secure? In the end the user has to trust the scripts delivered from our server anyway.

Jsonp to the rescue

But fortunately there exists another trick, namely jsonp. This is a neat trick where you add a “script” tag to your page which reference an external script. The external service (supporting jsonp) will then return a valid JavaScript which call’s the specified callback function with the response-data as input.

<script type="text/javascript"
src="http://somesite.no/someResource?jsonp=parseResponse"></script>


The Twitter feed

jQuery makes jsonp pretty simple and does all the hard work for us through the standard XHR-get call. You simply tell jQuery to fetch the data as jsonp with the “dataType” attribute. And of course, twitter supports jsonp.

In the example below I show how to fetch data from twitter using jsonp, and jQuery.

$.ajax({
    url: "http://search.twitter.com/search.json?q=%23test",
    dataType: "jsonp" }).success(function(data) {
    $.each(data.results, function(idx, result) {
      var time = "<span class='time'>"+ result.created_at + "</span>";
      var user = "<span class='user'>@" + result.from_user + "</span>: ";
      var tweet = $("<li>", {html: user + result.text + "<br />" + time});
      tweet.appendTo("#twitter");
    });
  });

As you can see it is pretty simple. One line to fetch the code and few lines of formatting. The final result is added to the “ul” container with id=”twitter”.

The benefits are:

  • less code
  • less server logic
  • less resources need on your part (the client fetches the data from twitter)
  • easier to implement
  • easier to maintain
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s