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)
- <!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=iso-8859-1" />
- <title>Ajax Login Form using jQuery, PHP, PDO, MySQL and Bootstrap | Mitrajit's Tech Blog</title>
- <link rel="stylesheet" href="bootstrap/css/bootstrap.min.css" />
- <!--<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>-->
- <script type="text/javascript" src="js/jquery.min.js"></script>
- <script type="text/javascript" src="bootstrap/js/bootstrap.min.js"></script>
- <script type="text/javascript" src="js/mtb.js"></script>
- <style>
- .form-check-label {
- background-image:url(images/error.png);
- background-position:left;
- background-repeat:no-repeat;
- padding-left:1.5rem;
- }
- .btn-success {
- cursor:pointer;
- }
- </style>
- </head>
- <body>
- <div class="container">
- <form class="form-horizontal" method="POST" id="login_form">
- <div class="row">
- <div class="col-md-4"></div>
- <div class="col-md-4">
- <h2>User Login</h2>
- <hr>
- </div>
- </div>
- <div class="row">
- <div class="col-md-4"></div>
- <div class="col-md-4">
- <div class="form-group has-danger">
- <div class="input-group mb-2 mr-sm-2 mb-sm-0">
- <div class="input-group-addon" style="width: 2.6rem"><i class="fa fa-at"><img src="images/username.png" width="20" /></i></div>
- <input type="text" name="username" class="form-control" id="username" placeholder="Username" autocomplete="off" required autofocus>
- </div>
- </div>
- </div>
- </div>
- <div class="row">
- <div class="col-md-4"></div>
- <div class="col-md-4">
- <div class="form-group">
- <div class="input-group mb-2 mr-sm-2 mb-sm-0">
- <div class="input-group-addon" style="width: 2.6rem"><i class="fa fa-key"><img src="images/password.png" width="20" /></i></div>
- <input type="password" name="password" class="form-control" id="password" placeholder="Password" required>
- </div>
- </div>
- </div>
- </div>
- <div class="row">
- <div class="col-md-4"></div>
- <div class="col-md-4">
- <input type="submit" class="btn btn-success" value="Login">
- <label class="form-check-label">
- <span class="text-danger align-middle" id="errorMsg"></span>
- </label>
- </div>
- </div>
- </form>
- </div>
- </body>
- </html>
Look at the above HTML code. It is very simple. Bootstrap 4 is used here. So, the Ajax login formis responsive in design.
- <input type="text" name="username" class="form-control" id="username" placeholder="Username" required autofocus>
- <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)
- $(document).ready(function() {
- $("#login_form").submit(function(e){
- e.preventDefault();
- $.ajax({
- url:'check_authentication.php',
- type:'POST',
- data: {username:$("#username").val(), password:$("#password").val()},
- success: function(resp) {
- if(resp == "invalid") {
- $("#errorMsg").html("Invalid username and password!");
- } else {
- window.location.href= resp;
- }
- }
- });
- });
- });
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)
- <?php
- try {
- $db = new PDO('mysql:host=localhost;dbname=DATABASE_NAME;charset=utf8mb4', 'USERNAME', 'PASSWORD');
- $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
- $db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
- } catch (PDOException $e) {
- echo "Connection failed : ". $e->getMessage();
- }
- ?>
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)
- <?php
- session_start();
- include("db.php");
- ?>
- <?php
- if(isset($_POST['username']) && $_POST['username'] != '' && isset($_POST['password']) && $_POST['password'] != '') {
- $username = trim($_POST['username']);
- $password = trim($_POST['password']);
- if($username != "" && $password != "") {
- try {
- $query = "select * from `user_login` where `username`=:username and `password`=:password";
- $stmt = $db->prepare($query);
- $stmt->bindParam('username', $username, PDO::PARAM_STR);
- $stmt->bindValue('password', $password, PDO::PARAM_STR);
- $stmt->execute();
- $count = $stmt->rowCount();
- $row = $stmt->fetch(PDO::FETCH_ASSOC);
- if($count == 1 && !empty($row)) {
- /******************** Your code ***********************/
- $_SESSION['sess_user_id'] = $row['id'];
- $_SESSION['sess_username'] = $row['username'];
- $_SESSION['sess_name'] = $row['name'];
- echo "home.php";
- } else {
- echo "invalid";
- }
- } catch (PDOException $e) {
- echo "Error : ".$e->getMessage();
- }
- } else {
- echo "Both fields are required!";
- }
- } else {
- header('location:./');
- }
- ?>
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)
- <?php
- session_start();
- if(isset($_SESSION['sess_user_id']) && $_SESSION['sess_user_id'] != "") {
- echo '<h1>Welcome '.$_SESSION['sess_name'].'</h1>';
- } else {
- header('location:./');
- }
- ?>
After successful login user will redirect to the home.php otherwise it will redirect to the index.php page.
Database Table
- CREATE TABLE `user_login` (
- `id` int(11) NOT NULL,
- `name` varchar(255) NOT NULL,
- `username` varchar(255) NOT NULL,
- `password` varchar(255) NOT NULL
- ) ENGINE=MyISAM DEFAULT CHARSET=latin1;
- INSERT INTO `user_login` (`id`, `name`, `username`, `password`) VALUES
- (1, 'Sachin Tendulkar', 'sachin', '123456'),
- (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.
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
ReplyDeleteYour blog provided us with valuable information to work with. Each & every tips of your post are awesome. Thanks a lot for sharing. Keep blogging..
ReplyDeleteBetting Script