Login with ajax in PHP, MySQL

If you want to create a login form that will not reload after clicking the submit button. Then you should make the Login with Ajax in PHP, MySQL

The Ajax Login form is very useful to sign in quickly to the database without refreshing the web page. So. It is frequently used in most web applications to make their registration form userfriendly & attractive.

In this tutorial, I have shared some simple steps to create the login/sign-in form using jquery Ajax in PHP & MySQL.

Steps to Create Login Form using Ajax, PHP

Learn Also –

Registration Form using Ajax, MySQL

Check Username availability using Ajax, PHP & MySQL

Check if an Email already exists in the Database using Ajax, PHP & MySQL

Now, Let’s start the coding to create the Ajax login form with the following simple steps –

1. Create Ajax Login Directory

First of all, You should create the following directory structure to build the login form.

source-code/
    |__database.php
    |__login.php
    |__dashboard.php
    |__user-details.php
    |__logout.php
    |__login.js

2. Create a Database Connection

File Name – database.php

<?php

$hostname     = "localhost";
$username     = "root";
$password     = "Coding@734";
$databasename = "codingstatus";
// Create connection
$conn = mysqli_connect($hostname, $username, $password, $databasename);

// Check connection
if (!$conn) {
    die("Unable to Connect database: " . mysqli_connect_error());
}
?>

 

3. Create a Login Form

To create the Login form UI, You have to follow the following points –

  • Create a basic HTML structure
  • Include the bootstrap5 CDN
  • Create a form with id ‘loginForm’
  • Also, create some input fields for emailAddress, password & submit button.
  • Include the jQuery CDN
  • Include the login.js

File Name – index.php

<!DOCTYPE html>
<html lang="en">
<head>
  <title>Bootstrap Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css" rel="stylesheet">

</head>
<body>

<div class="container">
    <div class="row">
        <div class="col-sm-4">

    <!--===== Registration Form ============-->
    <h3 class="mt-3 text-success text-center">Ajax Login Form</h3>
    <p class="text-center" id="msg"></p>
    <form id="loginForm" method="post">
    
      <div class="mb-3 mt-3">
          <input type="email" class="form-control" placeholder="Email Address" name="emailAddress">
        </div>
        <div class="mb-3 mt-3">
          <input type="password" class="form-control" placeholder="Password" name="password">
        </div>
      

      <button type="submit" class="btn btn-primary">Login</button>
    </form>
        <!--===== Registration Form ============-->

        </div>
        <div class="col-sm-8">

        </div>
    </div>
 
</div>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="login.js"></script>
</body>
</html>

 

4. Send Login Request with Ajax

Now, We have to write Ajax code to process the login credential to the PHP script. So, create a login.php and write the jquery Ajax code. This code will execute when the user submits the form after filling out their registration.

To write an Ajax code for login, you have to follow the following points –

  • Apply the submit event on the form id ‘loginForm’
  • Define the e.preventDefault to prevent the form from the reloading
  • Implement the next steps within the $.ajax()
  • define the form method post
  • define the PHP file path – login.php
  • also, serialize the input data using serialize() method
  • define the success to get the  success response
  • redirect to the dashboard.php using indow.location.href

File Name – login.js

$(document).on('submit','#loginForm',function(e){
    e.preventDefault();
   
    $.ajax({
    method:"POST",
    url: "login.php",
    data:$(this).serialize(),
    success: function(data){
   
    if(data === 'success') {
        window.location.href="dashboard.php";
    } else {
        $('#msg').html(data);
        $('#loginForm').find('input').val('')
    }
     
}});
});

 

5. Get Login Response with PHP & MySQL

Now, We have to check the login credential in the database, So, create a login.php file and write the PHP code. The code of this file will run while the Ajax code will be executed and sent to the post request.

To process login credential, you have to write PHP code with the following points-

  1. Include the database.php file
  2. and assign connection variable $conn to the $db
  3. Create a custom function loginUser() with two parameters $db and $userData.
  4. write a MySQLi query to insert data into the database,
  5. And then call the created function loginUser()

File Name – login.php

<?php

include_once("database.php");
$db = $conn;

define('tableName', 'users');
$userData = $_POST;

loginUser($db, $userData);

function loginUser($db, $userData) {

    $emailAddress   = $userData['emailAddress'];
    $password       = $userData['password'];
   

    if(!empty($emailAddress) && !empty($password)){

        
        $query = "SELECT emailAddress, password FROM ".tableName;
        $query .= " WHERE emailAddress = '$emailAddress' AND password = '$password'";
        $result = $db->query($query);
        if($result->num_rows > 0) {
           session_start();
           $_SESSION['userId'] = $emailAddress;
           echo "success";
        } else {
            echo "Wrong email and password";
        }
     
   } else {
      echo "All Fields are required";
   }
}

 

6. Create a Dashboard with User Details

After login, you need to redirect to the dashboard. So You can get the logged-in user details on the dashboard page.

File Name – dashboard.php

<!DOCTYPE html>
<html lang="en">
<head>
  <title>Welcome to Dashboard</title>
  
</head>
<body>
<h1>Welcome to Dashboard</h1>
<?php
include("user-details.php");

$userDetails = getUserbyId();

$firstName = $userDetails['firstName'];
$lastName = $userDetails['lastName'];
$fullName = $firstName." ".$lastName;
?>
<h3><?php echo $fullName; ?></h3>
<a href="logout.php">Logout</a>

</body>
</html>

 

7. Get Logged in User Details

You can use the following code to get the logged in user details from the database.

File Name – user-details.php

<?php
session_start();
$userId = $_SESSION['userId'];

include_once("database.php");
$db = $conn;

define('tableName', 'users');

if(!$userId){
  header("location:index.php");
}

function getUserbyId(){
    
    global $db;
    $userId = $_SESSION['userId'];
    $data = [];

    $query = "SELECT firstName, lastName FROM ".tableName;
    $query .= " WHERE emailAddress = '$userId'";

    $result = $db->query($query);
    
    if($result->num_rows > 0) {
      $data = $result->fetch_assoc(); 
    } else {
       header("location:index.php");
    }

    return $data;
}

8. Create Logout in PHP

To logout, You need to destroy session and redirected to the login page.

File Name – logout.php

<?php
session_start();
session_destroy();
header("location:index.php");


?>

9. Test Ajax Login Yourself

Now, You can text the Ajax login form by opening it in the web browser.

When you open the login form will get the email address and Password fields

After that Enter the login credential and submit the form. after that, you will be logged in successfully without reloading the web page and redirected to the dashboard page.