Display Tweets With jQuery and JSON

Posted on: February 8th, 2013

WARNING: The below code is deprecated as of June 11, 2013. I’ve created a snippet that’s updated here: Twitter Feed With PHP and JSON using API v1.1

For those of you looking for how to display Tweets with jQuery and JSON, here’s the code (explanation afterward):

// Declare variables to hold twitter API url and user name
    var twitter_api_url = 'http://search.twitter.com/search.json';
    var twitter_user    = 'johnbhartley';
    
    // Enable caching
    jQuery.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(
        // change the rpp=3 to whatever number you want
        twitter_api_url + '?callback=?&rpp=3&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 = '<li>';
                    
                    tweet_html    += tweet.text;
                    tweet_html    += '<div class="tweet_hours">';
                    tweet_html    += '<a href="http://www.twitter.com/';
                    tweet_html    += twitter_user + '/status/' + tweet.id + '">' + hours;
                    tweet_html    += ' hours ago</a></li>';

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

                  // hide the loading message
                  jQuery('#loadingmessage').hide(); 
              
            });
        }
    );

After you’ve popped that into your functions.js file (or whatever file you’re using), you just have to place the #tweet_container somewhere on your page, like so:

<!-- loading message with gif -->
<div id="loadingmessage">
   <!-- I was using WordPress, thus the bloginfo -->
   <img src="<?php bloginfo('template_url'); ?>/images/load.gif" />
   <br />Loading
</div>

<!-- tweets load here -->
<ul id="tweet_container"></ul>

I got the above code primarily from here, but there are some modifications. I’m still tweaking and modifying this code, but I’m pretty happy with how well it works.

By pinging the Twitter API on the client-side, you won’t have to worry about reaching the 150/hr limit, unless someone is crazy and tries to refresh 151 times in an hour.

I had tried caching my tweets using PHP and WordPress transients (more on this later), but it wasn’t working right. The only explanation that I could come up with, along with a colleague was that the Rackspace Cloud Hosting had a shared IP and was pinging the API from the same IP over 150 times. Whether that is accurate or not has yet to be proven or disproven, but I’m digging further into it.

One caveat is with the display of “hours ago”, if the tweet is one hour old it shows as “1 hours ago” (bad grammerz). It’s not perfect, but it’s pretty easy to implement. Give it a shot and feel free to show me a better way to do it. I’m pretty sure there’s some oauth stuff I need to figure out as well, so if you have any insight, please share.

Featured image found here.

Tags: , , , , , , ,

previous post: PHP not recognized as an internal or external command next post: Turn an Old Picture Frame into Responsive Wireframe