info343/minilabs/10/solution/minilab10-ex2.js

// minilab10-ex2.js
// Sample JavaScript solution for Mini-lab 10: AJAX
// (Example solution for Exercise 2.)
// INFO 343, Autumn 2012
// Morgan Doocy

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

// Make an Ajax request to fetch 'snippet.txt'.
function fetchClick() {
   $.ajax('snippet./*[<ins>]*/txt/*[</ins>]*/', {
      succes: injectSnippet,
      error: ajaxError
   });
}

// Inject the received data into #output.
function injectSnippet(data) {
/*[<ins>]*/   var lines = data.split('\n');
   var $ul = $('<ul>');
   $.each(lines, function(i, line) {
      var $li = $('<li>').text(line);
      $ul.append($li);
   });
   $('#output').append($ul);/*[</ins>]*/
}

// Display an alert with useful debugging information. (Called in case of an
// error in an Ajax request.)
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);
}