Login Page with PHP, jQuery, and Ajax

In this tutorial, we'll create a simple login page using PHP, jQuery, and AJAX.

Login Page with jQuery and Ajax

Contents

Database table

We are using users table to validate a user.

CREATE TABLE `users` (
  `id` int(11) NOT NULL,
  `username` varchar(80) NOT NULL,
  `name` varchar(80) NOT NULL,
  `password` varchar(80) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

2) Configuration

Creating a config.php file for define database and other configuration.

<?php

session_start(); /* Session Start name */

$host = "localhost"; /* Database Host name */
$user = "root"; /* Database User */
$password = ""; /* Database Password */
$dbname = "tutorial"; /* Database name */

$con = mysqli_connect($host, $user, $password,$dbname);
// Check connection is established or not. if not then stop execution with Connection failed error
if (!$con) {
 die("Connection failed: " . mysqli_connect_error());
}

3) HTML

Creating a index.php file. In it creating two input type elements for entering username and password and a button to submit the form and triggers AJAX call by submitevent.

<div id="login-box" class="col-md-12">
<form id="login-form" class="form" action="" method="post">
   <h3 class="text-center text-info">Login</h3>
      <div class="form-group">
      <label for="username" class="text-info">Username:</label><br>
      <input type="text" name="username" id="username" class="form-control">
   </div>
   <div class="form-group">
      <label for="password" class="text-info">Password:</label><br>
      <input type="text" name="password" id="password" class="form-control">
   </div>
   <div class="form-group submit_div">                               
      <input type="submit" name="btn_submit" class="btn btn-info btn-md" value="submit">
   </div>
</form>
</div>
Login Page

4) jQuery

Triggers AJAX call by submitevent, First we get value of username and password by their id’s. Pass this value in AJAX request.

   <script>
            $(document).ready(function(){
                $("#login-form").submit(function(e){
                     e.preventDefault();
                    // Get user input and trim it.
                    var username = $('#username').val().trim(); 
                    var password = $('#password').val().trim();           
                    if(username != '' &&  password !=''){        
                        $.ajax({
                            url: 'ajaxfile.php',// php file path
                            type: 'post',// method
                            data: {username: username, password: password},// Data send in json form
                            success: function(response){                
                                if(response=='validUser'){                               
                                  document.location = "home.php";
                                 }else{
                                  alert("Please check username and password.");
                                } 
                             }
                        });
                    }else{
                        $("#uname_response").html("");
                    }            
                });
            });
      </script>

5) PHP

Create a ajaxfile.php file.

First we check the username and password is set or not. If username and password are not empty then we execute a SELECT query to get user record on the basis of username and password.

Set “username” in session $_SESSION['username'] and return validUser.message otherwise return invalidUser message.

<?php

include 'config.php';
if(isset($_POST['username']) && isset($_POST['password']) ){     
       // Escapes special characters in a string for use in an SQL query,
       $username = mysqli_real_escape_string($con,$_POST['username']);
       $password = mysqli_real_escape_string($con,$_POST['password']);
       $UserData=array();
       // check username and password is empty or not.
       if ($username != "" && $password != ""){        
           $sql_query = "select * from users where username='".$username."' and password='".$password."'";
           //run query
           $result = mysqli_query($con,$sql_query);
           //Fetch userdata from result.
           $UserData = mysqli_fetch_array($result); 
           if(!empty($UserData)){
             $_SESSION['username'] = $username;             
               echo 'validUser';
             }else{
              echo 'invalidUser';
            }
        }
} 

7) Demo

Here, are some valid usernames – admin, brad and all have the same password – 12345. please try with this credentials.

8) Conclusion

In this tutorial, we showed how you can create a simple login page with PHP, MySQL, jQuery and AJAX.

Be First to Comment

Leave a Reply

Your email address will not be published.