How to Create a Lookup Form with Ajax

  • google plus

In Brief...

In some cases, you need to get quick information from a database, but you don't want to process an entire page. For example, you may have a form for requesting information about an order. The form might have multiple fields, one of which is the order number. The order number is not required, but if it's filled in it must match an existing order number in the database. Rather than waiting to check the order number until the user fills out and submits the entire form, you can use Ajax to flag a bad order number as soon as the user tabs out of that field.

Take our Ajax Training course for free.

See the Course Outline and Register

Instructions

A simple sample interface is shown below.

Sample Lookup Form Interface

When the user enters an order number that is not in the database, an error is displayed and the submit button becomes disabled.

Lookup Form with Error

When the user enters a valid order number, an icon is displayed indicating that the order number exists and the submit button becomes enabled.

Lookup Form Success

Here's how to create this lookup form:

  1. Create an HTML form and a script for sending the form data to a server-side script after a value is entered for the order number. Here's an example form and script.
    
    <!DOCTYPE HTML>
    <html>
    <head>
        <meta charset="UTF-8">
        <title>Order 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(order) {
                var orderNum = order.value;
                var xmlhttp = new XMLHttpRequest();
                var btnSubmit = document.getElementById("SubmitButton");
                var output = document.getElementById("OrderNumError");
    
                btnSubmit.disabled = true;
                if (orderNum.length == 0) { //OK to submit
                    output.innerHTML = "";
                    btnSubmit.disabled = false;
                    return true;
                }
                if (isNaN(orderNum)) { //Error
                    output.innerHTML = "Must be numeric.";
                    order.style.color = "red";
                    btnSubmit.disabled = true;
                    return true;
                }
    
                //Look up order number in database
                xmlhttp.open("GET", "Lookup?orderNum=" + orderNum, true);
    
                xmlhttp.onreadystatechange = function () {
                    if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                        lookupResults(xmlhttp);
                    }
                }
                xmlhttp.send(null);
    
                function lookupResults(xmlhttp) { //Callback function
                    if (xmlhttp.responseText.indexOf("success") == -1) { //Error: no match
    
                        output.innerHTML = "No such order number.";
                        order.style.color = "red";
                        btnSubmit.disabled = true;
                    } else {
                        output.innerHTML = "<img src='check.gif'>";
                        order.style.color = "green";
                        btnSubmit.disabled = false;
                    }
                }
    
                return false;
            }
            window.addEventListener(window,"load", function() {
                var order = document.getElementById("OrderNum");
                window.addEventListener(order, "blur", function() {
                     lookup(order);
                 });
             });
    
        </script>
    </head>
    <body>
    <form id="LookupForm" onsubmit="alert('Form would submit.'); return false;">
        <h1>Lookup Form</h1>
        <p>Enter an order number.</p>
        <div class="FormRow">
            <label for="OrderNum">Order Number:</label>
            <input type="text" size="10" id="OrderNum" name="OrderNum">
            <span id="OrderNumError"></span>
        </div>
        <div class="FormRow">
            <label for="Comments">Comments:</label><br>
            <textarea id="Comments" name="Comments" cols="40" rows="4"></textarea>
        </div>
        <div class="FormRow">
            <input type="submit" id="SubmitButton" value="Submit">
        </div>
    </form>
    </body>
    </html>
    
  2. Use a server-side script to accept the data from the Ajax request, do a database query, and return the result.
    
    app.get('/Lookup', function(req, res) {
        var orderNum = req.param('orderNum');
        var sql = "SELECT OrderID FROM Orders WHERE OrderID = " + orderNum;
        db.serialize(function() {
        db.get(sql, function(err, row) {
            if(err !== null) {
                res.status(500).send("An error has occurred -- " + err);
            } else {
                if (row) {
                    res.status(200);
                    return res.send("success");
                } else {
                    res.status(200);
                    return res.send("failed");
                }
            }
        });
        });
    });
    
                

Author: Chris Minnick

Chris is a prolific author and trainer, and the CEO of WatzThis?. His published books include Writing Computer Code, JavaScript for Kids, Coding with JavaScript For Dummies, Beginning HTML5 and CSS3 For Dummies, Webkit For Dummies, CIW eCommerce Certification Bible, and New Riders' XHTML.

Discuss