info343/lectures/jsonp-apis/files/tweets.js

// tweets.js
// JavaScript code for Tweets lecture example
// INFO 343, Autumn 2012
// Morgan Doocy

// When the page is ready, use JSONP to fetch recent tweets with the search term
// 'beer'.
$(document).ready(function() {
   $.ajax('http://search.twitter.com/search.json', {
      data: { q: "beer" }, // search.json?q=beer
      dataType: 'jsonp', // MUST include this to fetch data from another domain!
      success: injectTweet,
      error: ajaxError
   });
});

// Alert some information about the search query, and inject the first tweet's
// text into the page.
function injectTweet(data) {
   alert("Search for '" + data.query + "' completed in " + data.completed_in + " seconds.");
   var $p = $('<p>').text("The first tweet says: '" + data.results[0].text + "'");
   $p.appendTo('#output');
}

// Alert a useful debugging message based on information provided by jQuery.
// (Provided ajaxError function from lecture slides.)
function ajaxError(jqxhr, type, error) {
   var msg = "An Ajax error occurred!\n\n";
   if (type == 'error') {
      if (jqxhr.readyState == 0) {
         // Request was never made - security block?
         msg += "Looks like the browser security-blocked the request.";
      } else {
         // Probably an HTTP error.
         msg += 'Error code: ' + jqxhr.status + "\n" + 
                   'Error text: ' + error + "\n" + 
                   'Full content of response: \n\n' + jqxhr.responseText;
      }
   } else {
      msg += 'Error type: ' + type;
      if (error != "") {
         msg += "\nError text: " + error;
      }
   }
   alert(msg);
}