info343/labs/7/solution/urban-xml-single.js

document.observe("dom:loaded", function() {
   $("lookup").observe("click", doLookup);
   doLookup();
});

function doLookup() {
   new Ajax.Request("../urban.php",
      {
         method: "get",
         onSuccess: gotResult,
         onFailure: ajaxFailure,
         onException: ajaxFailure,
         parameters: {
            "term": $("term").value,
            "format": "xml"
         }
      }
   );
}

function gotResult(ajax) {
   var root = ajax.responseXML.firstChild;
   var error = root.getAttribute("error");
   
   if (error) {
      $("result").innerHTML = error;
   } else {
      var definition = document.createElement("p");
      var example = document.createElement("p")
      var permalink = $(document.createElement("p"));
      example.className = "example";
   
      var entry = root.getElementsByTagName("entry")[0];
      var definitionNode = entry.getElementsByTagName("definition")[0];
      definition.innerHTML = definitionNode.firstChild.nodeValue;

      var exampleNode = entry.getElementsByTagName("example")[0];
      example.innerHTML = exampleNode.firstChild.nodeValue;
      
      var link = $(document.createElement('a'));
      link.href = entry.getAttribute('permalink');
      link.innerHTML = "permalink";
      permalink.appendChild(link);
   
      $("result").innerHTML = "";
      $("result").appendChild(definition);
      $("result").appendChild(example);
      $("result").appendChild(permalink);
   }
}

// provided Ajax failure code (displays a useful alert when something goes
// wrong with the Ajax request)
function ajaxFailure(ajax, exception) {
   alert("Error making Ajax request:" + 
      "\n\nServer status:\n" + ajax.status + " " + ajax.statusText + 
      "\n\nServer response text:\n" + ajax.responseText);
   if (exception) {
      throw exception;
   }
}