Ajax Login Script with jQuery, PHP MySQL and Bootstrap

This tutorial will explain you, how to create a Login Script using jQuery Ajax with PHP MySQL, well this is my continuation post after Registration post using jQuery and Ajax, so in this tutorial i am going to create a simple login form using Bootstrap. email and password will be validate if user leave it empty after it a form will br submitted using $.ajax() method and send the users value to the main login page all the process will done without page refresh, before proceed you can go through the demo and download the script, let’s start the coding.

Ajax Login Script with jQuery, PHP MySQL and Bootstrap

 

read also : Ajax Registration Script with jQuery, PHP, MySQL

Database and Table

I have used here the previously created database and table which are used in ajax registration post, use the following code to create table in database “dbregistration”


CREATE TABLE IF NOT EXISTS `tbl_users` (
  `user_id` int(11) NOT NULL AUTO_INCREMENT,
  `user_name` varchar(25) NOT NULL,
  `user_email` varchar(60) NOT NULL,
  `user_password` varchar(255) NOT NULL,
  `joining_date` datetime NOT NULL,
  PRIMARY KEY (`user_id`)
) 

dbconfig.php

Database configuration file, modify username, password and database values as per your need.

<?php
 $db_host = "localhost";
 $db_name = "dbregistration";
 $db_user = "root";
 $db_pass = "";
 
 try{
  
  $db_con = new PDO("mysql:host={$db_host};dbname={$db_name}",$db_user,$db_pass);
  $db_con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
 }
 catch(PDOException $e){
  echo $e->getMessage();
 }
?>

Simple User Login Form

To load BootStrap design we have to add following two css bootstrap files just above the closing </head> tag

<link href="bootstrap/css/bootstrap.min.css" rel="stylesheet" media="screen">
<link href="bootstrap/css/bootstrap-theme.min.css" rel="stylesheet" media="screen">

create a new file and save it as index.php with the following code, this is our main login page contains html user friendly login form which will accepts email, password and of course validation is must so validation is there.

<div class="signin-form">

 <div class="container">
     
        
       <form class="form-signin" method="post" id="login-form">
      
        <h2 class="form-signin-heading">Log In to WebApp.</h2><hr />
        
        <div id="error">
        <!-- error will be shown here ! -->
        </div>
        
        <div class="form-group">
        <input type="email" class="form-control" placeholder="Email address" name="user_email" id="user_email" />
        <span id="check-e"></span>
        </div>
        
        <div class="form-group">
        <input type="password" class="form-control" placeholder="Password" name="password" id="password" />
        </div>
       
      <hr />
        
        <div class="form-group">
            <button type="submit" class="btn btn-default" name="btn-login" id="btn-login">
      <span class="glyphicon glyphicon-log-in"></span> &nbsp; Sign In
   </button> 
        </div>  
      
      </form>

    </div>
    
</div>

login_process.php

Contains only PHP code, this will verify email and password values in database, this file will work silently at back-end and call via $.ajax() method using jQuery code. if the login was success it gives ok message or if fails it will print wrong details message.

<?php
 session_start();
 require_once 'dbconfig.php';

 if(isset($_POST['btn-login']))
 {
  $user_email = trim($_POST['user_email']);
  $user_password = trim($_POST['password']);
  
  $password = md5($user_password);
  
  try
  { 
  
   $stmt = $db_con->prepare("SELECT * FROM tbl_users WHERE user_email=:email");
   $stmt->execute(array(":email"=>$user_email));
   $row = $stmt->fetch(PDO::FETCH_ASSOC);
   $count = $stmt->rowCount();
   
   if($row['user_password']==$password){
    
    echo "ok"; // log in
    $_SESSION['user_session'] = $row['user_id'];
   }
   else{
    
    echo "email or password does not exist."; // wrong details 
   }
    
  }
  catch(PDOException $e){
   echo $e->getMessage();
  }
 }

?>

Script.js

JavaScript/jQuery code which is responsible to do all the things silently, this will call “login_process.php” through $.ajax() method and id “response” is ok then it will redirect to the home page, if not it will display appropriate message within “#error” div. this script is completed with proper validation.

$('document').ready(function()
{ 
     /* validation */
  $("#login-form").validate({
      rules:
   {
   password: {
   required: true,
   },
   user_email: {
            required: true,
            email: true
            },
    },
       messages:
    {
            password:{
                      required: "please enter your password"
                     },
            user_email: "please enter your email address",
       },
    submitHandler: submitForm 
       });  
    /* validation */
    
    /* login submit */
    function submitForm()
    {  
   var data = $("#login-form").serialize();
    
   $.ajax({
    
   type : 'POST',
   url  : 'login_process.php',
   data : data,
   beforeSend: function()
   { 
    $("#error").fadeOut();
    $("#btn-login").html('<span class="glyphicon glyphicon-transfer"></span> &nbsp; sending ...');
   },
   success :  function(response)
      {      
     if(response=="ok"){
         
      $("#btn-login").html('<img src="btn-ajax-loader.gif" /> &nbsp; Signing In ...');
      setTimeout(' window.location.href = "home.php"; ',4000);
     }
     else{
         
      $("#error").fadeIn(1000, function(){      
    $("#error").html('<div class="alert alert-danger"> <span class="glyphicon glyphicon-info-sign"></span> &nbsp; '+response+' !</div>');
           $("#btn-login").html('<span class="glyphicon glyphicon-log-in"></span> &nbsp; Sign In');
         });
     }
     }
   });
    return false;
  }
    /* login submit */
});

home.php

this is our members home page and only members can access it, this file will opened via ajax, and if session is empty it will redirect to the login/index page.

<?php
session_start();

if(!isset($_SESSION['user_session']))
{
 header("Location: index.php");
}

include_once 'dbconfig.php';

$stmt = $db_con->prepare("SELECT * FROM tbl_users WHERE user_id=:uid");
$stmt->execute(array(":uid"=>$_SESSION['user_session']));
$row=$stmt->fetch(PDO::FETCH_ASSOC);

?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Login Form using jQuery Ajax and PHP MySQL</title>
<link href="bootstrap/css/bootstrap.min.css" rel="stylesheet" media="screen"> 
<link href="bootstrap/css/bootstrap-theme.min.css" rel="stylesheet" media="screen"> 
<link href="style.css" rel="stylesheet" media="screen">

</head>

<body>

<div class="container">
    <div class='alert alert-success'>
  <button class='close' data-dismiss='alert'>&times;</button>
   <strong>Hello '<?php echo $row['user_name']; ?></strong>  Welcome to the members page.
    </div>
</div>

</div>
<script src="bootstrap/js/bootstrap.min.js"></script>
</body>
</html>

logout.php

destroy the session to logout the user and redirects to the login/index page.

<?php
 session_start();
 unset($_SESSION['user_session']);
 
 if(session_destroy())
 {
  header("Location: index.php");
 }
?>

that’s it, we have created here a simple login script with Ajax, jQuery, PHP, MySQL with BootStrap design, well this is a continuation part of my previously posted tutorial. Hope you like it.