Tuesday 25 September 2018

Ajax login form using jQuery, PHP, PDO, MySQL and Bootstrap

Ajax login form is mainly used when you want to log in to your website by submitting the login form without any page refresh or redirection. This tutorial shows you how to create Ajax login form using jQuery, PHP, PDO, MySQL, and Bootstrap. By using Ajax we can accomplish the whole login process without any page refresh or reloading. In the following example, we will use PDO (PHP Data Objects) for MySQL connection and other CRUD operations.  You may also like —

HTML – AJAX Login Form (index.php)

  1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  2. <html xmlns="http://www.w3.org/1999/xhtml">
  3. <head>
  4. <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
  5. <title>Ajax Login Form using jQuery, PHP, PDO, MySQL and Bootstrap | Mitrajit's Tech Blog</title>
  6. <link rel="stylesheet" href="bootstrap/css/bootstrap.min.css" />
  7. <!--<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>-->
  8. <script type="text/javascript" src="js/jquery.min.js"></script>
  9. <script type="text/javascript" src="bootstrap/js/bootstrap.min.js"></script>
  10. <script type="text/javascript" src="js/mtb.js"></script>
  11. <style>
  12. .form-check-label {
  13. background-image:url(images/error.png);
  14. background-position:left;
  15. background-repeat:no-repeat;
  16. padding-left:1.5rem;
  17. }
  18. .btn-success {
  19. cursor:pointer;
  20. }
  21. </style>
  22. </head>
  23. <body>
  24. <div class="container">
  25. <form class="form-horizontal" method="POST" id="login_form">
  26. <div class="row">
  27. <div class="col-md-4"></div>
  28. <div class="col-md-4">
  29. <h2>User Login</h2>
  30. <hr>
  31. </div>
  32. </div>
  33. <div class="row">
  34. <div class="col-md-4"></div>
  35. <div class="col-md-4">
  36. <div class="form-group has-danger">
  37. <div class="input-group mb-2 mr-sm-2 mb-sm-0">
  38. <div class="input-group-addon" style="width: 2.6rem"><i class="fa fa-at"><img src="images/username.png" width="20" /></i></div>
  39. <input type="text" name="username" class="form-control" id="username" placeholder="Username" autocomplete="off" required autofocus>
  40. </div>
  41. </div>
  42. </div>
  43. </div>
  44. <div class="row">
  45. <div class="col-md-4"></div>
  46. <div class="col-md-4">
  47. <div class="form-group">
  48. <div class="input-group mb-2 mr-sm-2 mb-sm-0">
  49. <div class="input-group-addon" style="width: 2.6rem"><i class="fa fa-key"><img src="images/password.png" width="20" /></i></div>
  50. <input type="password" name="password" class="form-control" id="password" placeholder="Password" required>
  51. </div>
  52. </div>
  53. </div>
  54. </div>
  55. <div class="row">
  56. <div class="col-md-4"></div>
  57. <div class="col-md-4">
  58. <input type="submit" class="btn btn-success" value="Login">
  59. <label class="form-check-label">
  60. <span class="text-danger align-middle" id="errorMsg"></span>
  61. </label>
  62. </div>
  63. </div>
  64. </form>
  65. </div>
  66. </body>
  67. </html>
Look at the above HTML code. It is very simple. Bootstrap 4 is used here. So, the Ajax login formis responsive in design.
  1. <input type="text" name="username" class="form-control" id="username" placeholder="Username" required autofocus>
  2. <input type="password" name="password" class="form-control" id="password" placeholder="Password" required>
To validate user inputs we attached jQuery form validation in this example simply by attaching required attribute within the input fields.

Ajax Call – Ajax Login Form (mtb.js)

  1. $(document).ready(function() {
  2. $("#login_form").submit(function(e){
  3. e.preventDefault();
  4. $.ajax({
  5. url:'check_authentication.php',
  6. type:'POST',
  7. data: {username:$("#username").val(), password:$("#password").val()},
  8. success: function(resp) {
  9. if(resp == "invalid") {
  10. $("#errorMsg").html("Invalid username and password!");
  11. } else {
  12. window.location.href= resp;
  13. }
  14. }
  15. });
  16. });
  17. });
We will handle the login form submission by using jQuery Ajax and send Ajax request to check_authentication.php further login process will perform.

MySQL Database Connection Using PDO (db.php)

  1. <?php
  2. try {
  3. $db = new PDO('mysql:host=localhost;dbname=DATABASE_NAME;charset=utf8mb4', 'USERNAME', 'PASSWORD');
  4. $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  5. $db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
  6. } catch (PDOException $e) {
  7. echo "Connection failed : ". $e->getMessage();
  8. }
  9. ?>
PDO (PHP Data Objects) is more secure and has a much nicer interface, you will end up being more productive, and write safer and cleaner code.

PHP – User Authentication (check_authentication.php)

  1. <?php
  2. session_start();
  3. include("db.php");
  4. ?>
  5. <?php
  6. if(isset($_POST['username']) && $_POST['username'] != '' && isset($_POST['password']) && $_POST['password'] != '') {
  7. $username = trim($_POST['username']);
  8. $password = trim($_POST['password']);
  9. if($username != "" && $password != "") {
  10. try {
  11. $query = "select * from `user_login` where `username`=:username and `password`=:password";
  12. $stmt = $db->prepare($query);
  13. $stmt->bindParam('username', $username, PDO::PARAM_STR);
  14. $stmt->bindValue('password', $password, PDO::PARAM_STR);
  15. $stmt->execute();
  16. $count = $stmt->rowCount();
  17. $row = $stmt->fetch(PDO::FETCH_ASSOC);
  18. if($count == 1 && !empty($row)) {
  19. /******************** Your code ***********************/
  20. $_SESSION['sess_user_id'] = $row['id'];
  21. $_SESSION['sess_username'] = $row['username'];
  22. $_SESSION['sess_name'] = $row['name'];
  23. echo "home.php";
  24. } else {
  25. echo "invalid";
  26. }
  27. } catch (PDOException $e) {
  28. echo "Error : ".$e->getMessage();
  29. }
  30. } else {
  31. echo "Both fields are required!";
  32. }
  33. } else {
  34. header('location:./');
  35. }
  36. ?>
The above PHP code is responsible for checking the user details based on the username and password the user provided.

Home Page – Successful login (home.php)

  1. <?php
  2. session_start();
  3. if(isset($_SESSION['sess_user_id']) && $_SESSION['sess_user_id'] != "") {
  4. echo '<h1>Welcome '.$_SESSION['sess_name'].'</h1>';
  5. } else {
  6. header('location:./');
  7. }
  8. ?>
After successful login user will redirect to the home.php otherwise it will redirect to the index.php page.

Database Table

  1. CREATE TABLE `user_login` (
  2. `id` int(11) NOT NULL,
  3. `name` varchar(255) NOT NULL,
  4. `username` varchar(255) NOT NULL,
  5. `password` varchar(255) NOT NULL
  6. ) ENGINE=MyISAM DEFAULT CHARSET=latin1;
  7. INSERT INTO `user_login` (`id`, `name`, `username`, `password`) VALUES
  8. (1, 'Sachin Tendulkar', 'sachin', '123456'),
  9. (2, 'Sourav Ganguly', 'sourav', '456789');
First, create the user_login table then insert the data into that table.

Live Demo And Complete Source Code – Ajax Login Form

Try the live demo example by click on the DEMO link. Download the complete source code from the Download link below. Please like and share this tutorial with others.

2 comments:

  1. Wow, this is fascinating reading. I am glad I found this and got to read it. Great job on this content. I liked it a lot. Thanks for the great and unique info. bootstrap button classes

    ReplyDelete
  2. Your blog provided us with valuable information to work with. Each & every tips of your post are awesome. Thanks a lot for sharing. Keep blogging..
    Betting Script

    ReplyDelete