• google plus

How to Create a Login Form with Ajax

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
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.
About Webucator

Webucator provides instructor-led training to students throughout the US and Canada. We have trained over 90,000 students from over 16,000 organizations on technologies such as Microsoft ASP.NET, Microsoft Office, Azure, Windows, Java, Adobe, Python, SQL, JavaScript, Angular and much more. Check out our complete course catalog.