Login page with jQuery and AJAX

A Login page is one of the basic requirements when creating a registration based website where the user can register to the website and sign in to its account to manage.

In this case, you can use AJAX to create a user-friendly login page.

With AJAX you can directly check the entered username and password are correct or not in MySQL database without reloading the whole page.

If the user is registered then redirect the user to a home page otherwise display an error.

Login page with jQuery and AJAX


Contents

  1. Table structure
  2. Configuration
  3. HTML
  4. PHP
  5. jQuery
  6. Demo
  7. Conclusion

1. Table structure

I am using users table in the tutorial example.

CREATE TABLE `users` (
  `id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
  `username` varchar(80) NOT NULL,
  `name` varchar(80) NOT NULL,
  `password` varchar(80) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

2. Configuration

Create a new config.php file for the database connection.

Completed Code

<?php
session_start();
$host = "localhost"; /* Host name */
$user = "root"; /* User */
$password = ""; /* Password */
$dbname = "tutorial"; /* Database name */

$con = mysqli_connect($host, $user, $password,$dbname);
// Check connection
if (!$con) {
  die("Connection failed: " . mysqli_connect_error());
}

3. HTML

Creating a simple login page which contains two input box for entering username and password.

A submit button to send AJAX request with jQuery on click.

Completed Code

<div class="container">

    <div id="div_login">
        <h1>Login</h1>
        <div id="message"></div>
        <div>
            <input type="text" class="textbox" id="txt_uname" name="txt_uname" placeholder="Username" />
        </div>
        <div>
            <input type="password" class="textbox" id="txt_pwd" name="txt_pwd" placeholder="Password"/>
        </div>
        <div>
            <input type="button" value="Submit" name="but_submit" id="but_submit" />
        </div>
    </div>

</div>

4. PHP

Create a new checkUser.php file.

Check the $_POST username and password values in the users table.

If the query returns more than 0 value means the user exists in the table then initialize $_SESSION['uname'] variable with username and echo 1.

If the query return 0 then echo 0.

Completed Code

<?php
include "config.php";

$uname = mysqli_real_escape_string($con,$_POST['username']);
$password = mysqli_real_escape_string($con,$_POST['password']);

if ($uname != "" && $password != ""){

    $sql_query = "select count(*) as cntUser from users where username='".$uname."' and password='".$password."'";
    $result = mysqli_query($con,$sql_query);
    $row = mysqli_fetch_array($result);

    $count = $row['cntUser'];

    if($count > 0){
        $_SESSION['uname'] = $uname;
        echo 1;
    }else{
        echo 0;
    }

}

home.php

When login user is valid then redirect the user to this page.

If the $_SESSION['uname'] variable is not initiated then redirect to index.php webpage.

Created an anchor tag for logout.

Completed Code

<?php
include "config.php";

// Check user login or not
if(!isset($_SESSION['uname'])){
   header('Location: index.php');
}

?>
<!doctype html>
<html>
    <head></head>
    <body>
        <h1>Homepage</h1>
        <br>
        <a href="logout.php">Logout</a>
    </body>
</html>

Logout

Create a logout.php file.

Destroy the SESSION and redirect to index.php.

Completed Code

<?php

// Destroy 
session session_destroy(); 
header('Location: index.php');

5. jQuery

On login button click send AJAX request where pass entered username and password as data.

Redirect to home.php when the response is equal to 1 otherwise show error message on the screen.

Completed Code

$(document).ready(function(){
    $("#but_submit").click(function(){
        var username = $("#txt_uname").val().trim();
        var password = $("#txt_pwd").val().trim();

        if( username != "" && password != "" ){
            $.ajax({
                url:'checkUser.php',
                type:'post',
                data:{username:username,password:password},
                success:function(response){
                    var msg = "";
                    if(response == 1){
                        window.location = "home.php";
                    }else{
                        msg = "Invalid username and password!";
                    }
                    $("#message").html(msg);
                }
            });
        }
    });
});

6. Demo

Here, are some valid usernames – yssyogesh, bsonarika, vishal, vijay and all have the same password – 12345. View in a new tab.


7. Conclusion

AJAX login page saves time by not reloading the webpage on every wrong attempt and provides a better user-interface.

If you want to know how to create a register page then you can view the following tutorial.

If you found this tutorial helpful then don't forget to share.

25 thoughts on “Login page with jQuery and AJAX”

  1. Please Can you help me out, i am using your code exactly as is, with the same database.Though whenever iinsert the user name and password,eg sona 123456.It just comes up with the incorret username or password alert. Please could you kindly assist me.

    Reply
      • I have created the database. All record are in it. Though it still says invalid username or password. Isn’t this program suppose to check if they record are present, and if they are. Then they can login.

  2. Thanks for your login form example . Could u please give some example about the purchase or sales invoice which have the following fields. format.

    ItemID Item Name Qty Rate Total
    101 Item 1 5 3 15
    102 Item 2 6 7 42
    103 Item 3 7 8 56
    Total Amount 113
    The invoice should be in grid form and when i select item id then item name will automaticallly display from the database. The grid should contain edit,delete,save,search,print,csv,pdf format. Kindly resolve this problem immdeiately. both itemid and itemname should be autocomplete.

    Reply
  3. What’s going on with your Login Page?
    When I input the data that you gave me to redirect it to home.php but I cannot see the word Hello World.Because I see that the file home.php you put the h1 tag with the text Hello World. What should I do now to display the text Hello World onto the server when I redirect it?

    Reply
  4. please help below with a problem
    thankyou

    $(“#loginform”).submit(function(event){
    //prevent default php processing
    event.preventDefault();
    //collect user inputs
    var datatopost = $(this).serializeArray();
    console.log(datatopost);
    //send them to login.php using AJAX
    $.ajax({
    url: “login.php”,
    type: “POST”,
    data: datatopost,
    success: function(data){
    if(data.includes(“success”)){
    window.location = “mainpageloggedin.php”;
    }else{
    $(“#loginmessage”).html(data);
    }
    },
    error:function(){
    $(“#loginmessage”).html(“There was an error with the Ajax Call. Please try again later.”);
    }
    });
    });

    Reply
  5. I never comment on Blogs…But Thanku. This is the first time , I am commenting as your blog made my day……Thank u so much..GOD Bless you!!!

    Reply
  6. this approach with ajax is good and i managed to use it. i login using username, password and usertype…but i want to also parse the user’s firstname and lastname onto the destination page after login. i have so far not succeeded. any help?

    Reply
  7. Hello, thanyou for this tut. Unfortunately I get this error when executing the login… Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result, boolean given

    Can you help please ?

    Reply

Leave a Reply to Lushen Cancel reply