How to Create a Lookup Form with Ajax

See Ajax: Tips and Tricks for similar articles.

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.

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");
                }
            }
        });
        });
    });
    
                

Related Articles

  1. How to Make a Cross-origin Ajax Request
  2. How to Create a Login Form with Ajax
  3. How to Set Up Automatic Session Timeout with Ajax
  4. How to Use the Callback Function in Ajax
  5. How to Develop a Web Application with Ajax
  6. How to Make GET, POST, and HEAD Requests Using Ajax
  7. How to Use the jQuery ajax() Method
  8. How to Create a Lookup Form with Ajax (this article)
  9. How to Create a Slideshow with Ajax
  10. How to Handle the Response from the Server in Ajax
  11. How to Set Up for Ajax Training on Windows
  12. Inline Editing Using Ajax
  13. How to Create a Navigable Table with Ajax