info343/lectures/intro-to-ajax/files/quote.js

// quote.js
// JavaScript code for "Quote of the Day" Ajax lecture example
// (Originally from CSE 190 M, Marty Stepp)
// INFO 343, Autumn 2012
// Morgan Doocy

// When the page is ready, attach a click handler to the #fetch button.
$(document).ready(function() {
   $('#fetch').click(fetchClick);
});

// Make an Ajax request to quote.php to fetch a new quote.
function fetchClick() {
   $.ajax('/lectures/intro-to-ajax/quote.php', {
      success: injectQuote,
      error: ajaxError,
   });
}

// Inject the received quote into the #quote paragraph.
function injectQuote(data) {
   $('#quote').text(data);
}

// 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 never went out - 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);
}