[Modal] AJAX Login Form using Bootstrap, PHP OOP, MySQL & jQuery

Hi! This time I have come up with jquery ajax login form using bootstrap, php oop & mysql database. And the interesting part is, this login form's design resembles Google login form but ours is a modal form built with Bootstrap. I always liked Google's simple and clean style and wanted to try it here and got the chance now. Since our login is a modal form, I'm going to use AJAX to submit form without refresh. So today's tutorial is about building Modal Login Script using AJAX, PHP OOP & MySQL.

As for user interface I have used bootstrap but with pretty good customization to the css. Also used PHP for server-side processing and MySQL for backend database. The script has Object oriented programming approach and includes complete login logout system in php.

php-ajax-login-script-bootstrap

How to Create AJAX Login Form using PHP OOP & MySQL?

We'll need database for the demo. So let's create it first.

Step-1) Create MySQL DB & Tables

CREATE DATABASE IF NOT EXISTS `db_login`;
USE `db_login`;

CREATE TABLE IF NOT EXISTS `users` (
  `id` int(9) NOT NULL AUTO_INCREMENT,
  `name` varchar(30) NOT NULL,
  `email` varchar(60) NOT NULL,
  `password` varchar(40) NOT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `email` (`email`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=2;

INSERT INTO `users` (`id`, `name`, `email`, `password`) VALUES (1, 'Test', 'test@mydomain.com', '098f6bcd4621d373cade4e832627b4f6');

Step-2) Build PHP Class

Next create the php class for login module. The class includes three functions 1. userLogin() to authenticate user, 2. userLogout() for logging out user and destroy session and 3. escapeString() which is used to escape user input to avoid sql injection.

UserClass.php

<?php
class UserClass
{
    private $db;
    
    // constructor
    function __construct($db)
    {
        $this->db = $db;
    }
    
    function userLogin($email, $pwd)
    {
        $result = $this->db->query("SELECT * FROM users WHERE email = '" . $email. "' and password = '" . md5($pwd) . "'");
        
        if ($result->num_rows > 0)
        {
            // success
            @session_start();
            $row = $result->fetch_assoc();
            $_SESSION['user_id'] = $row['id'];
            $_SESSION['user_name'] = $row['name'];
            return true;
        }
        else
        {
            // login fail
            return false;
        }

    }
    
    function userLogout()
    {
        session_destroy();
        unset($_SESSION['user_id']);
        unset($_SESSION['user_name']);
        return;
    }
    
    function escapeString($str) {
        return $this->db->real_escape_string($str);
    }
}
?>

Step-3) Database Connection

Next we'll create a separate file for database connection. It uses mysqli library for establishing php connection to mysql server. Please make sure to change the connection details like username, password to yours.

dbconnect.php

<?php
// mysql connection
$hostname = 'localhost';
$username = 'root';
$password = '';
$database = 'db_login';

$db = new mysqli($hostname, $username, $password, $database);
if($db->connect_errno)
    die('Error ' . $this->db->connect_error);

include_once('UserClass.php');
$con = new UserClass($db);
?>

Step-4) Build Modal Login Form

We need to create our user interface. Create a file named 'index.php' in application root and build modal form using bootstrap. The modal login form wouldn't be visible at first and would be shown when the user clicks on 'Login' menu on top navigation.

index.php

<?php @session_start(); ?>
<!DOCTYPE html>
<html>
<head>
    <title>AJAX PHP Login Script using Bootstrap</title>
    <meta content="width=device-width, initial-scale=1.0" name="viewport" >
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" type="text/css" rel="stylesheet" />
    <link href="css/custom.css" rel="stylesheet" type="text/css" />
</head>
<body>

<nav class="navbar navbar-inverse" role="navigation">
    <div class="container-fluid">
        <div class="navbar-header">
            <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#navbar1">
                <span class="sr-only">Toggle navigation</span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
            </button>
            <a class="navbar-brand" href="index.php">Koding Made Simple</a>
        </div>
        <div class="collapse navbar-collapse" id="navbar1">
            <ul class="nav navbar-nav pull-right">
                <?php if (isset($_SESSION['user_id'])) { ?>
                    <li><p class="navbar-text">Hi! <?php echo $_SESSION['user_name']; ?></p></li>
                    <li><a href="dashboard.php">Dashboard</a></li>
                    <li><a href="logout.php">Logout</a></li>
                <?php } else { ?>
                    <li><a href="#">Sign Up</a></li>
                    <li class="active"><a href="#" data-toggle="modal" data-target="#login-modal">Login</a></li>
                <?php } ?>
            </ul>
        </div>
    </div>
</nav>

<!-- modal login form -->
<div id="login-modal" class="modal fade" aria-labelledby="myModalLabel" aria-hidden="true" tabindex="-1" role="dialog">
    <div class="modal-dialog">
        <div class="login-modal-container">
            <form id="login-form" role="form">
                <div class="modal-body">
                    <h2>Login To Your Account </h2>
                    <div id="err-msg"></div>
                    <div class="form-group">
                        <input type="text" id="email" name="email" placeholder="Your email address" class="form-control input-lg" />
                    </div>
                    <div class="form-group">
                        <input type="password" id="password" name="password" placeholder="Password" class="form-control input-lg" />
                    </div>
                    <div class="form-group">
                        <div id="captcha"></div>
                    </div>
                    <div class="form-group">
                        <input type="submit" id="login" name="login" value="Sign In" class="btn btn-primary btn-block btn-lg" />
                    </div>
                </div>
                <div class="modal-footer">
                    Don't have an account? <a href="#">Sign Up here</a>
                </div>
            </form>
        </div>
    </div>
</div>
<div class="container text-center">
<h1>index page</h1>
<p>Add your content here...</p>
</div>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="js/script.js"></script>
</body>
</html>

This login form includes jquery validation and both 'Email' & 'Password' fields are required. Input fields will be highlighted with red color if user fails to enter the details.

Once the user fill in the credentials and clicks on 'Sign In' button, form data will be posted to the backend php script using jQuery Ajax() method.

It will be processed there and if user credentials are valid they will taken to the Dashboard page. Else proper error message will be shown in the login form.

Step-5) PHP Login Process

Next create 'login.php', here is the form data will be submitted and processed against database.

login.php

<?php
include_once('dbconnect.php');

if (isset($_POST['login']))
{
    $uemail = $con->escapeString($_POST['email']);
    $upwd = $con->escapeString($_POST['password']);
    echo $con->userLogin($uemail, $upwd);
}
?>

Step-6) Create User Dashboard Page

This is the dashboard page where the users will be redirected once they are logged in to the website. This page remains inaccessible for guests. Only logged in users get to access it and if not they will be redirected to index page.

dashboard.php

<?php
@session_start();

if(!isset($_SESSION['user_id'])) {
    header('Location: index.php');
}
?>
<!DOCTYPE html>
<html>
<head>
    <title>AJAX PHP Login Script using Bootstrap</title>
    <meta content="width=device-width, initial-scale=1.0" name="viewport" >
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" type="text/css" rel="stylesheet" />
    <link href="css/custom.css" rel="stylesheet" type="text/css" />
</head>
<body>

<nav class="navbar navbar-inverse" role="navigation">
    <div class="container-fluid">
        <div class="navbar-header">
            <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#navbar1">
                <span class="sr-only">Toggle navigation</span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
            </button>
            <a class="navbar-brand" href="index.php">Koding Made Simple</a>
        </div>
        <div class="collapse navbar-collapse" id="navbar1">
            <ul class="nav navbar-nav pull-right">
                <li><p class="navbar-text">Hi! <?php echo $_SESSION['user_name']; ?></p></li>
                <li><a href="logout.php">Logout</a></li>
            </ul>
        </div>
    </div>
</nav>

<div class="container text-center">
<h1>User Dashboard</h1>
<p>Add your content here...</p>
</div>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="js/script.js"></script>
</body>
</html>

Step-7) Add Logout Process

Then create a file 'logout.php' which will be executed when user clicks on 'Logout' button. The script destroys user session and flush out the user data stored in session variables.

logout.php

<?php
@session_start();
include_once('dbconnect.php');
$con->userLogout();
header('Location: index.php');
?>

Step-8) Script.js

This is the JavaScript file loaded in the index page. It contains all jquery functions we have used to validate the login form and Ajax function to submit the user data to login.php file.

$('document').ready(function() {
    $('#email').on('focus', function () {
        $('#email').removeClass('error');
    });

    $('#email').on('blur', function () {
        if ($('#email').val() == '') {
            $('#email').addClass('error');
        }
    });

    $('#password').on('focus', function () {
        $('#password').removeClass('error');
    });

    $('#password').on('blur', function () {
        if ($('#password').val() == '') {
            $('#password').addClass('error');
        }
    });

    $('#login-form').on('submit', function (e) {
            e.preventDefault();
            $('#err-msg').html('');
            var err = false;
            if ($('#email').val() == '') {
                $('#email').addClass('error');
                err = true;
            }
            if ($('#password').val() == '') {
                $('#password').addClass('error');
                err = true;
            }
            if (err == true) {
                return false;
            }
            
            $.ajax({
            type: 'POST',
            url: 'login.php',
            data: $('#login-form').serialize() + '&' + $('#login').attr('name') + '=' + $('#login').val(),
            success: function(status){
                if (status == true) {
                    $('#login').val('Signing in...');
                    setTimeout('window.location.href = "dashboard.php";',3000);
                } else {
                    $('#err-msg').html('<div class="alert alert-danger text-center">Invalid email or password!</div>');
                    $('#email').val('');
                    $('#password').val('');
                }
            }
        });
    });
});

Step-9) custom.css

Finally our custom stylesheet for the login form. It includes the css I have used to override bootstrap styles and some additional styles for designing the login form.

* {
    border-radius: 2px !important;
    -moz-border-radius: 2px !important;
    -webkit-border-radius: 2px !important;
}

.login-modal-container  {
    max-width: 350px;
    width: 100% !important;
    background-color: #F7F7F7;
    margin: 0 auto;
    padding: 20px;
    box-shadow: 0px 2px 2px rgba(0, 0, 0, 0.3);
    overflow: hidden;
}

.login-modal-container .modal-body  {
    padding: 20px 10px;
}

.login-modal-container .modal-footer  {
    text-align: center;
    margin: 0 10px;
}

.login-modal-container h2  {
    text-align: center;
    font-size: 25px;
    margin-bottom: 25px;
}

.login-modal-container input {
    font-size: 16px;
}

.login-modal-container  input[type=submit]  {
    background-color: #4D90FE;
    border: 2px solid #4D90FE;
    text-shadow: 0 1px rgba(0,0,0,0.1); 
}

.login-modal-container  input[type=submit]:hover  {
    background-color: #357AE8;
    border: 2px solid #357AE8;
}

.error {
    background-color: #F2DEDE;
}

Please make sure to include 'custom.css' after loading 'bootstrap.css' for the styles to kick in and take effect.

Done! We have finished the coding part. Now to test this ajax login script, run index.php and you will see page like this.

ajax-login-logout-script-php-mysql-index-page

Click on 'Login' button on the top and it will launch the modal login form.

bootstrap-ajax-login-form-modal

Click on the 'Sign In' button without providing email or password will trigger validation error and the corresponding fields will be highlighted with red color like this,

ajax-login-form-jquery-validation

If the email and password doesn't match up with the database details, then you'll be shown error message like this,

jquery-ajax-login-form-invalid-login

To test successful login, enter 'test@mydomain.com' for email and 'test' for password field and click on 'Sign In' button.

ajax-php-login-form-signing-in

These are the valid login details, so you will see 'Signing in...' message on the form and will be redirected to Dashboard page.

bootstrap-ajax-login-script-dashboard-page

Since you are logged in to the system, you will see 'Logout' button on top menu. Clicking it will logout you and redirects to index page. That accounts for our ajax login logout system.

Download

Also Read: User Login and Registration Script using PHP & MySQL

Don't Miss: CRUD (Insert, Fetch, Update & Delete) in PHP & MySQL

Well! That explains about building ajax login script using php oop, mysql & jquery. I hope you liked this tutorial. Meet you in another interesting post.

2 comments:

  1. this post is very interesting. i really enjoyed to read this. whatever you said i really wanna do that.thank you.

    Digital marketing company in india

    ReplyDelete
  2. i need to do this on code igniter how do i do that???

    ReplyDelete