Fetching tweets with jQuery and the Twitter JSON API

Just thought it’d be nice to share this little script that fetches tweets using a jQuery AJAX request and the Twitter API. The script is based on a snippet I picked up from my good friend Sven Lito.

I’ve added verbose comments in the code itself, so let’s keep this post short ;-)

You can see the working demo here: http://www.lupomontero.com/tuts/jQuery-TwitterAPI/index.html

The javascript

$(document).ready(function() {
    // Declare variables to hold twitter API url and user name
    var twitter_api_url = 'http://search.twitter.com/search.json';
    var twitter_user    = 'lupomontero';

    // Enable caching
    $.ajaxSetup({ cache: true });

    // Send JSON request
    // The returned JSON object will have a property called "results" where we find
    // a list of the tweets matching our request query
    $.getJSON(
        twitter_api_url + '?callback=?&rpp=5&q=from:' + twitter_user,
        function(data) {
            $.each(data.results, function(i, tweet) {
                // Uncomment line below to show tweet data in Fire Bug console
                // Very helpful to find out what is available in the tweet objects
                //console.log(tweet);

                // Before we continue we check that we got data
                if(tweet.text !== undefined) {
                    // Calculate how many hours ago was the tweet posted
                    var date_tweet = new Date(tweet.created_at);
                    var date_now   = new Date();
                    var date_diff  = date_now - date_tweet;
                    var hours      = Math.round(date_diff/(1000*60*60));

                    // Build the html string for the current tweet
                    var tweet_html = '<div class="tweet_text">';
                    tweet_html    += '<a href="http://www.twitter.com/';
                    tweet_html    += twitter_user + '/status/' + tweet.id + '">';
                    tweet_html    += tweet.text + '<\/a><\/div>';
                    tweet_html    += '<div class="tweet_hours">' + hours;
                    tweet_html    += ' hours ago<\/div>';

                    // Append html string to tweet_container div
                    $('#tweet_container').append(tweet_html);
                }
            });
        }
    );
});

The markup

<div id="tweet_container"></div>

Tags: , , ,

9 Responses to “Fetching tweets with jQuery and the Twitter JSON API”

  1. Eric Rosete says:

    Thank you for this! Short and to the point.

  2. admin says:

    Hi Eric,

    Thanks for the comment. Positive feedback is always welcome ;-)

    Lupo

  3. - i just love to Twitter everyday with my friends. Twitter is much better than blogging in my opinion and it is very addictive too.
    **** ..

  4. Eric Rosete says:

    I was just using this again and wanted to use a formatted date (MM/DD/YYYY) instead of the approximated time (X hours ago). Just thought I’d share.

    Change these lines:

    tweet_html += ” + hours;
    tweet_html += ‘ hours ago’;

    To this:

    tweet_html += ” + date_tweet.toLocaleDateString();
    tweet_html += ”;

    All you do is add .toLocaleDateString(); to the date_tweet variable. Also I took out the “hours ago” text since we’re not using hours.

  5. Lupo says:

    Thanks for the update…

    By the way, if you don’t need the ‘ hours ago’ bit simply get rid of the line where it gets concatenated to the tweet_html variable.

    So no need to keep the following line:

    tweet_html += ”;

    Peace,

    Lupo

  6. Caramoan says:

    Twitter is some ways is much better than blogging. I love to Twitter my everyday activities on my friends and relatives.
    ***

  7. Hatem says:

    Hey,

    I just came across this post, and i need something like that for my website.
    but when i try your code, and i change var twitter_user to my account. it doesn’t retrieve any tweets but if i keep it with your info it does! any ideas?

    Thanks

  8. Lupo says:

    Hi Hatem,

    Are there any recent tweets in your account? I’ve had the same problem before when I hadn’t tweeted for a few days…

    Let me know if that’s not the problem.

    Best,

    Lupo

  9. I like this code and I am trying to modify using CSS.

    I ‘d like to be able to add avatars, but am not having much luck.

    Any suggestions?

    Andy

Leave a Reply

Anti-Spam Protection by WP-SpamFree