Books

This page is a demonstration of how to enter parameters, search an XML file, and load a table with the results. It uses AJAX (JavaScript and XML) to implement this functionality, and CSS to do all the styling.

TitleAuthor
No resultNo result

First we start with the XML book list... (to be continued)

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<library xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
	<book>
		<isbn>9780749547929</isbn>
		<title>AA Caravan &amp; Camping France 2006</title>
		<author>AA Publishing</author>
	</book>
	<book>
		<isbn>9780749537555</isbn>
		<title>The AA Pub Guide 2004</title>
		<author>AA Publishing</author>
	</book>
</library>

Now let's look at some of the things we need to do... (to be continued)

function search(filename)
{
  // Get the library filename, and the search term
  var library_filename = document.getElementById("lib_file").value;
  var search_term = document.getElementById("search_on").value;

  // The div into which we put the table
  var table_div =     document.getElementById("table_div");

  // We want to search case-insensitive
  var search_regexp = new RegExp(search_term, "i");

  // Retrieve the given library file
  xmlhttp=new XMLHttpRequest();
  xmlhttp.open("GET",library_filename, false);
  xmlhttp.send();
  xmlDoc=xmlhttp.responseXML;

  var books=xmlDoc.getElementsByTagName("book");
  var title = "";
  var author = "";

  // Now search the response for the given string and create a table
  var tmpArray = [];
  var rowTemplate = "<tr><td>%title%<\/td><td>%author%<\/td><\/tr>";
  tmpArray[0] = '<table id="search_results" summary="">\n<thead><th>Title<\/th><th>Author<\/th><\/thead>\n<tbody id="data-area">';

  // Iterate through the books, looking for the search term, add if found
  for (var i = 0, k = 1, j = books.length; i < j; i++) {
    title = books[i].getElementsByTagName("title")[0].childNodes[0].nodeValue;
    author = books[i].getElementsByTagName("author")[0].childNodes[0].nodeValue;

    if ((title.search(search_regexp) != -1) || (author.search(search_regexp) != -1))
    {
      tmpArray[k] = rowTemplate.replace(/%(title|author)%/g, cvrt);
      k++;
    }
  }

  tmpArray[k] = "<\/tbody>\n<\/table>";
  table_div.innerHTML = tmpArray.join("\n");

  // This is the second time we get these elements, surely we can do better
  function cvrt()
  {
    return books[i].getElementsByTagName(arguments[1])[0].childNodes[0].nodeValue;
  }
  
}

Links

HTML5 Powered with CSS3 / Styling, and Semantics