How to Create a Login Form with Ajax

See Ajax: Tips and Tricks for similar articles.
Looking to improve your Ajax skills? Check out Webucator’s Ajax classes.

An Ajax login form can send data to the server and display an error message without requiring a page refresh. This can make the process of logging in less painful for the user. Here's how to program an Ajax login form.

  1. Create an HTML document.
    
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
    </head>
    <body>
    
    </body>
    </html>
            
  2. Create a script block inside your document and write a function named login() that will make the Ajax request when the form is submitted.
    
    function login(form) {
        var un = form.Username.value;
        var pw = form.Password.value;
        var xmlhttp = new XMLHttpRequest();
        xmlhttp.open("post", "Login", true);
        xmlhttp.onreadystatechange = function () {
            if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                loginResults();
            }
        }
    }
            
  3. Write an event listener that will register an eventListener for the form when the page loads.
    
    window.addEventListener(window,"load", function() {
        var loginForm = document.getElementById("LoginForm");
        window.addEventListener(loginForm, "submit", function() {
             login(loginForm);
         });
     });
                
  4. Create a form.
    
    <form id="LoginForm" onsubmit="return false">
        <h1>Login Form</h1>
        <div class="FormRow">
            <label for="Username">Username:</label>
            <input type="text" size="15" id="Username" name="Username">
        </div>
        <div class="FormRow">
            <label for="Password">Password:</label>
            <input type="password" size="15" id="Password" name="Password">
        </div>
        <div class="FormRow" id="LoginButtonDiv">
            <input type="submit" value="Login">
        </div>
        <div id="BadLogin">
            <p>The login information you entered does not match
            an account in our records. Please try again.</p>
        </div>
    </form>
            
  5. Write a function to receive the results of the Ajax login and display the response text.
    
    function loginResults() {
        var loggedIn = document.getElementById("LoggedIn");
        var badLogin = document.getElementById("BadLogin");
        if (xmlhttp.responseText.indexOf("failed") == -1) {
            loggedIn.innerHTML = "Logged in as " + xmlhttp.responseText;
            loggedIn.style.display = "block";
            form.style.display = "none";
        } else {
            badLogin.style.display = "block";
            form.Username.select();
            form.Username.className = "Highlighted";
            setTimeout(function() {
                badLogin.style.display = 'none';
            }, 3000);
        }
    }
            
  6. Test the form. This example code assumes that your login script is available at /Login, relative to the location of the script. You can customize the Login function and the path to your script for your own needs. Result of Running the Demo Scripts

Related Articles

  1. How to Make a Cross-origin Ajax Request
  2. How to Create a Login Form with Ajax (this article)
  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
  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