Creating a Simple Lookup Form - Exercise

Contact Us or call 1-877-932-8228
Creating a Simple Lookup Form - Exercise

Creating a Simple Lookup Form

Duration: 20 to 30 minutes.

In this exercise, you will create a lookup form that takes a year and returns the name of the person who was president that year. The page looks like this:Page

  1. From the command line, navigate to the directory AjaxApplications/Exercises/ and type npm install to install the needed Node.js modules.
  2. Also from the command line, type npm start to start the Node.js server.
  3. Open AjaxApplications/Exercises/server.js in your editor and review the "Lookup" route (the method which begins app.get('/Lookup', function(req, res) {). This route is complete. It expects a year to be passed in and returns, using the Lookup.jade template, an HTML string containing the names of the presidents who were in office that year.
  4. Open AjaxApplications/Exercises/Lookup.html in your editor and write all the JavaScript code for this page. The call to the server should look something like this: /Lookup?year=1801, where "1801" is the year entered by the user.
  5. Test your solution by opening http://localhost:8080/Lookup.html in the browser.

The server-side script is complete. The Node.js response route "Lookup" queries the database and returns all presidents for the given year, supplied as the GET parameter year:

app.get('/Lookup', function(req, res) {
    var year = req.param('year');
    presidentsdb.all("SELECT FirstName, LastName, StartYear, EndYear FROM Presidents WHERE StartYear <= " + year + " AND EndYear >= " + year, function(err, row) {
      if(err !== null) {
        res.status(500).send("An error has occurred -- " + err);
      } else {
        res.render('Lookup.jade', {presidents: row}, function(err, html) {
          res.status(200).send(html);
        });
      }
    });
});
				

The response is rendered via the template Lookup.jade template:

doctype html
html(lang="en")
  head
    title Lookup

  body
    - each pres in presidents
        p #{pres.FirstName} #{pres.LastName} (#{pres.StartYear} - #{pres.EndYear})

You'll do your work here on the client-side:

Solution:

AjaxApplications/Solutions/Lookup.html
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title>Lookup Form</title>
<link href="Lookup.css" type="text/css" rel="stylesheet">
<script type="text/javascript" src="lib.js"></script>
<script type="text/javascript">
	function lookUp(form) {
		var year = form.Year.value;
		var xmlhttp = new XMLHttpRequest();
		if (isNaN(year) || year.length != 4) {
			alert("Please enter a valid year.");
			return false;
		}
		if (year < 1789 || year > 1845) {
			alert("Please enter a year between 1789 and 1845.");
			return false;
		}

		xmlhttp.open("get", "Lookup?year=" + year, true);

		xmlhttp.onreadystatechange = function() {
			if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
				lookupResults(xmlhttp);
			}
		}
		xmlhttp.send(null);

		function lookupResults(xmlhttp) {
			var resultDiv = document.getElementById("LookupResults");
			resultDiv.innerHTML = xmlhttp.responseText;
		}
	}

	observeEvent(window, "load", function() {
		var form = document.getElementById("LookupForm");
		observeEvent(form, "submit", function() {
			lookUp(form);
		});
	});
</script>
</head>
<body>

<form id="LookupForm" onsubmit="return false;">
	<h1>Lookup Form</h1>
	<p>Enter a year between 1789 and 1845 to find out who was president that year.</p>
	<div class="FormRow">
		<label for="Year">Year:</label>
		<input type="text" size="5" id="Year" name="Year">
		<input type="submit" value="Lookup">
	</div>
	<hr>
	<div class="FormRow" id="LookupResults"></div>
</form>

</body>
</html>

We check first to test if the user-entered year is a number, is four digits in length, and falls between the date range indicated.

We then make a GET request to Lookup, passing along the year parameter.

We then set the innerHTML of div#resultDiv with the returned results.

Next