Ajax Login Script with jQuery, PHP MySQL and Bootstrap | Coding Cage

Ajax Login Script with jQuery, PHP MySQL and Bootstrap

By
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.



62 comments:

  1. Thanks for sharing the code. It was helpful to create login script using jQuery Ajax with PHP MySQL. Hire PHP developers from a skilled and experienced PHP web development company which provides excellent PHP development services.

    ReplyDelete
  2. Thanks for sharing the code. It was helpful to create login script using jQuery Ajax with PHP MySQL. but i get this warning and don't let me register :

    SQLSTATE[42000] [1044] Access denied for user 'sixoneth_fives'@'localhost' to database '_dbregistration' !

    thank you.

    ReplyDelete
    Replies
    1. Hello Iraj, please check username of your local server

      Delete
    2. I keep getting errors http://error404.000webhost.com/cpu-limit-reached.html , pm if u want to use a subdomain on my host.

      Delete
  3. Demo link not working, when i try to log in to mine using test, [email protected] i get message email or password does not exist.

    ReplyDelete
    Replies
    1. Hello Midas, please make sure you have entered correct details, and also check in your mysql table that details exist or not

      Delete
    2. Hello sir . I have a same problem with Mr. Midas. I have already check and re-check for a few times , the codes and also my sql table ( all details) and still get this error message "email or password does not exist." . Please help , how to solve it . It mean a lot sir.

      Delete
    3. Hello sir . I have a same problem with Mr. Midas. I have already check and re-check for a few times , the codes and also my sql table ( all details) and still get this error message "email or password does not exist." . Please help , how to solve it . It mean a lot sir.

      Delete
  4. Really nice tut! thanks for sharing.

    ReplyDelete
    Replies
    1. thanks for visiting fher
      do visit again :)

      Delete
  5. Nice tutorial, thank you!

    How can i redirect a user to his unique homepage with his email?

    like window.location.href = "[email protected]"

    Thank you!


    ReplyDelete
  6. Thanks for the tut! How can I redirect every user to his own page, e.g. by ID?

    Thank you!

    ReplyDelete
  7. I can not log in, notification email or password does not exist. ! always appear.
    although the email and password is matching. Please Help.

    ReplyDelete
  8. Awesome posts here.
    But, I set up the server but continuously getting login error "email or password does not exist. !"
    What could be the cause ?

    ReplyDelete
  9. can't sign in I've provided all appropriate details sir

    ReplyDelete
    Replies
    1. hello osampas, please let me know actual error, it's not enough to get ...

      Delete
  10. This user mail and password enter for correct only.
    But always showing the wrong username password.
    Then how to login?

    ReplyDelete
    Replies
    1. Hi SARATHI B
      I also got this error finally i found the password is in MD5
      u have to enter MD5 encrypt password to user_password column in table.
      hope this help

      Delete
    2. This code just is for login/logout after registration. To check whether the code works just insert some data (useraname and password) in the database using phpmyadmin.

      If you want a registration form you have to do it separately, it is not included in the code.

      Delete
    3. Yes the validation is looking for an md5 encrypted password . Either use the md5 function to insert encrypted psw into the table or remove md5 in line 10 login_process.php. Better to use encryption if you are using for a live site

      Delete
    4. MD5 crypt +1 :) thank's

      Delete
  11. Thank you for your code. How to register new account?

    ReplyDelete
    Replies
    1. Hello Wedotech,
      what you are looking for, there is tutorial on this blog about ajax registration please go through the posts...

      Delete
  12. Beautiful tutorial, thanks for sharing

    ReplyDelete
  13. Hello.
    Thank you for your tutorial, it helps me a lot.
    But I'm facing the problem of signing in. I entered the correct username and password but it still showed the error(email and password does not exist).
    I am a beginner, so please guide me. Thank you again.

    ReplyDelete
    Replies
    1. Hello Nabelle,
      it's not enough to get your error, may be credentials are actually wrong or try to echo sql queries which is used to login, hence it is working code

      Delete
  14. This comment has been removed by the author.

    ReplyDelete
  15. Hi!

    thanks for sharing the code, I tested in a localhost and works deluxe but changed to a productive server and send me error 500 my response headers are:

    Connection - closed;
    accept - */*;
    content-type application/x-www-form-urlencoded; charset utf-8;
    X-Requested-With XMLHttpRequest

    I hope someone can help me. thanks

    ReplyDelete
  16. hi,
    thanks for the tutorial.

    i have a problem at if(response=="ok"){...
    this just won't get executed.

    else{} part of the code works, if info is wrong but if it's ok nothing happens.
    i've tried removing the if statement and just put in alert(response) to see
    if something will happen, and the alert box does appear correctly for inputting correct and wrong information .

    why doesn't the if(...) part work?
    php file is ok.

    thanks for your help.

    ReplyDelete
    Replies
    1. hello there,
      it's working code i have tested it, did you make some changes in this script after downloading ...?

      Delete
    2. change echo ok with echo 1
      change response==ok with response==1

      now it works

      Delete
  17. u ve used mysqli pdo.. can i use only mysql ?? Is it safe to use mysql ?? for mysql what changes i need to do ??

    ReplyDelete
    Replies
    1. hi lonee, i have used here only PDO query not MySQLi and it is recommended to use b'coz mysql extensions are now deprecated, so switch-over from mysql to mysqli or pdo, i recommend you to use pdo cause it is safe to use.

      Delete
  18. i m totally new to pdo .. can u provide me some basic tutorial link .. That ll be a great help :)

    ReplyDelete
  19. still get this error message "email or password does not exist." . Please help , how to solve it .

    ReplyDelete
    Replies
    1. may by your database does'nt encrypt with md5
      try to below in login_process.php
      //$password = md5($user_password);
      $password =$user_password;

      Delete
    2. you are removing password encryption which is unsafe, md5 shouldnt be used any longer as is easily hacked, crypt() should now be used and is included in php from 5.3 >

      Delete
    3. Thanks , you are right

      Delete
    4. shouldnt be using md5 these days, totally insecure, the crypt() function is miles better and future proof

      Delete
  20. Hi sir. Thank you so much for this tutorial, but I've got some questions. I have like 3 usertypes in my website: superadmin, admin, member. And I've separted them in different folders. So for instance I have my folder named "Sample" and inside that folder I have SuperAdmin, Admin, Member. How can I have one login page or form for these different users? Btw, my login is in my sample/index.php . I really hope you can help me. Thank you!

    ReplyDelete
    Replies
    1. With an if statement you can achieve that, you redirect them to the respective page after checking their role, which you have to add to your database

      Delete
  21. The "Sign In" button gets stuck on "sending..." and doesn't ever log in (but also does not return an error). Anyone know what's going on?

    ReplyDelete
  22. how do I download this code for mac? there is no application available to open it. I have already tried simply typing out the code on this page but there seems to be A LOT of errors.

    ReplyDelete
  23. I finally got this working but I am also having the problem with the email and password not existing? Does anyone know how to fix this?

    ReplyDelete
  24. Hi! Your tutorial was really helpful, thank you for it!

    But I have a problem. I created registration and login functionality and it works. When I login and refresh the page ones it works fine. But when I click on some link or refresh for second time, it automaticaly log me out. I guess session expires somehow but I don't know how to fix it at this point and I would be happy for some help.

    Thank you very much!

    ReplyDelete
  25. Great Helpful, I have created another login form using Ajax, jQuery & PHP.
    Here is demo of Ajax Login Form Using jQuery and PHP

    ReplyDelete
  26. i would revise using md5 as its easily subject to brute force, i would have a read here:

    http://php.net/manual/en/faq.passwords.php#faq.passwords.fasthash

    ReplyDelete
  27. In my case line 21 in login_process.php didn't work:

    if($row['user_password']==$password){

    ...which I replaced it with:

    if(strcmp($row['user_password'], $user_password) == 0){

    I suspect it has with different versions of PHP.

    Hope that will help someone...

    ReplyDelete
  28. Hello, i have problem with "response", my "respone" is empty.
    I try to remove the script and use manual action form, and "ok" show.
    but when I use the script and use alert to show parameter response, and it still empty, need help pls..

    ReplyDelete
  29. SQLSTATE[HY000] [1049] Unknown database 'dbregistration'
    Notice: Undefined variable: db_con in C:\xampp\htdocs\Ajax-Login-Script-PHP\login_process.php on line 16

    Fatal error: Uncaught Error: Call to a member function prepare() on unknown in C:\xampp\htdocs\Ajax-Login-Script-PHP\login_process.php:16 Stack trace: #0 {main} thrown in C:\xampp\htdocs\Ajax-Login-Script-PHP\login_process.php on line 16
    !

    ReplyDelete
  30. SQLSTATE[HY000] [1049] Unknown database 'dbregistration'
    Notice: Undefined variable: db_con in C:\xampp\htdocs\Ajax-Login-Script-PHP\login_process.php on line 16

    Fatal error: Uncaught Error: Call to a member function prepare() on unknown in C:\xampp\htdocs\Ajax-Login-Script-PHP\login_process.php:16 Stack trace: #0 {main} thrown in C:\xampp\htdocs\Ajax-Login-Script-PHP\login_process.php on line 16
    !

    ReplyDelete
  31. thank you!
    this is a great tutorial!
    but, I got a question for you.
    How could I read user data by using ajax jQuery?

    ReplyDelete
  32. How do you configure your server/code (I think is the server) so the session never expires and you are always logged in until you log out (like Facebook). In your demo that happens, but when I put it on mine it times out after a while and you have to login again

    ReplyDelete
  33. How do you configure your server/code (I think is the server) so the session never expires and you are always logged in until you log out (like Facebook). In your demo that happens, but when I put it on mine it times out after a while and you have to login again

    ReplyDelete
  34. How do you configure your server/code (I think is the server) so the session never expires and you are always logged in until you log out (like Facebook). In your demo that is what happens, but when I put it on mine it times out after a while and you have to login again

    ReplyDelete
  35. Thank you for this tus. It help me more to do understand login logout with ajax sql :))

    ReplyDelete
  36. Working fine out of the box. No errors. Implemented in a existing website. Be sure for every php file you have to add
    session_start();

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

    On top to make sure everything is protected.

    ReplyDelete