info343/lectures/json-web-services/files/books.js

// books.js
// JavaScript code for "Books" lecture example
// INFO 343, Autumn 2012
// Morgan Doocy

// Location of web service on info343.ischool.uw.edu.
var WEB_SERVICE = '/lectures/json-web-services/books.php';

// Set ajaxError function to be error handler for all Ajax requests on the page.
$.ajaxSetup({ error: ajaxError });

// When the page is ready, attach event handlers and fetch list of categories.
$(document).ready(function() {
   // Fetch the list of categories, and inject them into #categories. (Making a
   // request to books.php without parameters will return a list of categories.)
   $.get(WEB_SERVICE, injectCategories);
   
   // Fetch books of selected category when #fetch is clicked.
   $('#fetch').click(fetchBooks);
});

// Create an <option> in the #categories dropdown for each category in the
// provided list of categories.
function injectCategories(categories) {
   for (var i = 0; i < categories.length; i++) {
      $('<option>').text(categories[i]).appendTo('#categories');
   }
}

// Initiate Ajax request to fetch list of books of the currently-selected category.
function fetchBooks() {
   $.ajax(WEB_SERVICE, {
      data: { category: $('#categories').val() }, // 'books.php?category=' + $('#categories').val()
      success: injectBooks
   });
}

// Inject the titles and authors of the given books into the #books list.
function injectBooks(books) {
   // Empty the #books list of any previous books.
   $('#books').empty();
   
   // Create a <li> for each book returned containing its title and author, and
   // inject into #books.
   for (var i = 0; i < books.length; i++) {
      var $li = $('<li>').text('"' + books[i].title + '" by ' + books[i].author);
      $li.appendTo('#books');
   }
}

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