Full Stack LAMP - MEAN Developer, Python developer. Certified Azure Developer. Freelance programmer/consultant/trainer.

Ajax Login form using PHP and MySQL

Today I would like to show you Ajax login functionality implementation using PHP and MySQL. We gonna use the MySQL PDO driver in this tutorial. PDO has a much nicer interface, you will end up being more productive, and write safer and cleaner code.

 Ajax Login form using PHP and MySQL

Create Ajax Login Form

Login Form

Create a file called login_form.php with the following code.

<div class="container">
        <h1>Login Page</h1>
        <div class="card">

            <div class="card-header">Login</div>

            <div class="card-body">

                <div id="error-msg" class="alert alert-danger" role="alert"></div>

                <form id="login-form" action="/login.php" method="post" name="login-form">
                <div class="mb-3">
                        <label for="email">Email address</label> 
                        <input id="email" class="form-control" name="email" type="email" placeholder="Enter email"></div>
                        <div class="mb-3">
                        <label for="password">Password</label> 
                        <input id="password" class="form-control" name="password" type="password" placeholder="Password">
                    </div>
                    <button id="login" class="btn btn-primary" type="submit">Login</button>
                </form>

            </div>
        </div>
    </div>

    <!-- Option 1: Bootstrap Bundle with Popper -->
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-ygbV9kiqUc6oa4msXn9868pTtWMgiQaeYH7/t7LECLbyPA2x65Kgf80OJFdroafW" crossorigin="anonymous"></script>

    <script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script>

    <script>
        $(function() {
            $("#error-msg").hide(); 
            $('#login').click(function(e) {

                let self = $(this);

                e.preventDefault(); // prevent default submit behavior

                self.prop('disabled', true);

                var data = $('#login-form').serialize(); // get form data

                // sending ajax request to login.php file, it will process login request and give response.
                $.ajax({
                    url: '/login.php',
                    type: "POST",
                    data: data,
                }).done(function(res) {
                    res = JSON.parse(res);
                    if (res['status']) // if login successful redirect user to secure.php page.
                    {
                        location.href = "secure.php"; // redirect user to secure.php location/page.
                    } else {

                        var errorMessage = '';
                        // if there is any errors convert array of errors into html string, 
                        //here we are wrapping errors into a paragraph tag.
                        console.log(res.msg);
                        $.each(res['msg'], function(index, message) {
                            errorMessage += '<div>' + message + '</div>';
                        });
                        // place the errors inside the div#error-msg.
                        $("#error-msg").html(errorMessage);
                        $("#error-msg").show(); // show it on the browser, default state, hide
                        // remove disable attribute to the login button, 
                        //to prevent multiple form submissions 
                        //we have added this attribution on login from submit
                        self.prop('disabled', false);
                    }
                }).fail(function() {
                    alert("error");
                }).always(function() {
                    self.prop('disabled', false);
                });
            });
        });
    </script>

Database Details

This tutorial assumes that you have the following user table structure in your database. For the sake of the example script, I have provided an insert query with test data.

CREATE TABLE IF NOT EXISTS `users` (
  `user_id` int(11) NOT NULL AUTO_INCREMENT,
  `first_name` varchar(255) NOT NULL,
  `last_name` varchar(255) NOT NULL,
  `email` varchar(255) NOT NULL,
  `password` varchar(255) NOT NULL,
  `date_added` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`user_id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=2;
--
-- Dumping data for table `users`
--
INSERT INTO `users` (`user_id`, `first_name`, `last_name`, `email`, `password`, `date_added`) VALUES
(1, 'Arjun', 'PHP', '[email protected]', '$2y$10$8mVSGv/bIGgcvCikXBPfTu7HfXMl3jqfiirtQGyRwV5bvOzNGmmLG', '2017-10-12 18:09:10');

You can generate password hash by using password_hash() function, example echo password_hash("password", PASSWORD_DEFAULT);.

Config.php

After importing the above table into your database. Create a file called config.php, where you gonna save information about MySQL Database configuration, you can use this file to save other config details too.

<?php
   define('DB_SERVER', 'localhost');
   define('DB_USERNAME', 'root');
   define('DB_PASSWORD', '');
   define('DB_DATABASE', 'php_ajax_login');
   $db = new PDO('mysql:host='.DB_SERVER.';dbname='.DB_DATABASE, DB_USERNAME, DB_PASSWORD);

Login

Create a file called login.php with the following code. This file will handle the login requests, It will validate user details against the database. Upon valid and successful login, it will start the user session, otherwise, it will throw the appropriate error message.

<?php
require_once 'config.php';

$error = array();
$res = array();

if (empty($_POST['email'])) {
    $error[] = "Email field is required";
}

if (empty($_POST['password'])) {
    $error[] = "Password field is required";
}
if (!empty($_POST['email']) && !filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
    $error[] = "Enter Valid Email address";
}

if (count($error) > 0) {
    $resp['msg'] = $error;
    $resp['status'] = false;
    echo json_encode($resp);
    exit;
}

$statement = $db->prepare("select * from users where email = :email");
$statement->execute(array(':email' => $_POST['email']));
$row = $statement->fetchAll(PDO::FETCH_ASSOC);
if (count($row) > 0) {
    if (!password_verify($_POST['password'], $row[0]['password'])) {
        $error[] = "Password is not valid";
        $resp['msg'] = $error;
        $resp['status'] = false;
        echo json_encode($resp);
        exit;
    }
    session_start();
    $_SESSION['user_id'] = $row[0]['user_id'];
    $resp['redirect'] = "dashboard.php";
    $resp['status'] = true;
    echo json_encode($resp);
    exit;
} else {
    $error[] = "Email does not match";
    $resp['msg'] = $error;
    $resp['status'] = false;
    echo json_encode($resp);
    exit;
}

secure.php

Create a file called secure.phpfile with the following code. On successful login, we will redirect the user to this page. Only authenticated users can access this page. If unauthorized users try to access this page, users will forcefully be redirected to the login page.

<?php
session_start();
if(empty($_SESSION['user_id'])){
   header('location: login_form.php');    
} else {
   echo 'Secure page!.';
   echo '<a href="/logout.php">logout';
}

logout.php

Create a file called logout.php and put the below code in the file.

<?php
session_start(); 
session_destroy(); 
header('location: login_form.php');

Once everything is in place head over to the browser with http://localhost/login_form.php you should get output something like the below image

Ajax Login form using PHP and MySQL
Ajax Login form using PHP and MySQL

I hope you like this Post, Please feel free to comment below, your suggestion and problems if you face - we are here to solve your problems.

0 0 votes
Article Rating
Subscribe
Notify of
guest

12 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments