Simplified AJAX Login Form Using PHP and jQuery

When it comes to websites and apps, logging in is the first step for many users. It's like unlocking a door to access personalized content or services. In this tutorial, we'll show you how to create a login system that's smooth, secure, and user-friendly. We'll use AJAX and PHP to make it happen. By the end, you'll have the skills to build a login form that's not just easy to use but also keeps user data safe. Ready to get started? Let's make logging in a breeze.

Directory structure

In this section, we'll discuss how to organize your project directory to maintain a clean and structured codebase. A well-organized directory structure makes it easier to manage files and resources.

The directory structure is organized as follows:

  • connection.php: This file establishes a database connection, ensuring secure data access.
  • index.php: The main entry point of your application where users can access the login form.
  • login.php: Handles user login requests using AJAX and PHP, validating user credentials.
  • logout.php: Implements a logout mechanism to securely end user sessions.
  • welcome.php: Displays a personalized welcome page upon successful login.
  • common.js: Contains JavaScript functions and utilities shared across your application.

Database Connection

The connection.php file establishes and maintains a secure connection to your database. This connection is essential for interacting with user data.

Create a file called connection.php and add below code:

<?php
// Database credentials.
define('DB_HOST','localhost'); // Host name
define('DB_USER','root');      // database user's name
define('DB_PASS','password');  // database user's password
define('DB_NAME','login');     // database name

// Create database connection.
try {
	$conn = new PDO("mysql:host=".DB_HOST.";dbname=".DB_NAME,DB_USER, DB_PASS);
} catch (PDOException $e) {
	echo "Error: " . $e->getMessage();
	exit();
}
?>

Create Table - Users SQL Query

We'll provide an SQL query to create the 'users' table in your database, ensuring secure storage of user credentials and related information.

CREATE TABLE IF NOT EXISTS `users`(
`id` int(10) NOT NULL AUTO_INCREMENT,
`name` varchar(20) NOT NULL,
`password` varchar(50) NOT NULL,
PRIMARY KEY (`id`)
)

Insert data into our table

Populate the 'users' table with sample data using INSERT statements. This step allows you to simulate user registration and test your login system. Run below query to insert user record to use in login demo. Here the password is testing and we are storing its md5 value into the database.

INSERT INTO `users` (`name`, `password`) VALUES('kevin', 'ae2b1fca515949e5d54fb22b8ed95575');

Login Form HTML File (index.php)

In the index.php file, create the HTML structure for the login form. Utilize Bootstrap for styling and enhance user experience. Create a file called index.php and add below code:

<!DOCTYPE html>
<html lang="en">
<head>
   <meta charset="UTF-8">
   <meta name="viewport" content="width=device-width, initial-scale=1.0">
	<title>Login Form</title>
	<!-- Include Bootstrap CSS -->
   <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
	<?php 
	session_start();
	if (isset($_SESSION['username'])) { ?>
		<a href='logout.php'>Logout</a>
	<?php } ?>
</head>
<body>
	<?php 
	if (empty($_SESSION['username'])) { ?>
		<div class="container mt-5" id="login_form">
			<div class="row justify-content-center">
			   <div class="col-md-6">
			       <div class="card">
			           <div class="card-header">
			               Login
			           </div>
			           <div class="card-body">
			           		<!-- Error Messages -->
			               <div class="alert" id="error-message" style="display: none;"></div>
			               <form action="login.php">
			                   <div class="form-group">
			                       <label for="username">Username</label>
			                       <input type="text" class="form-control" name="username" id="username" placeholder="Enter your username">
			                   </div>
			                   <div class="form-group">
			                       <label for="password">Password</label>
			                       <input type="password" class="form-control" name="password" id="password" placeholder="Enter your password">
			                   </div>
			                   <button type="submit" class="btn btn-primary" id="login">Submit</button>
			               </form>
			           </div>
			       </div>
			   </div>
			</div>
		</div>
	<?php }?>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="common.js"></script>    
</body>
</html>

Handle Login Form Request with Ajax(common.js)

The common.js file houses shared JavaScript functions and utilities used throughout your application. It streamlines code management and promotes code reusability. Create a file called common.js and add below code:

$(document).ready(function() {
   $("#login").click(function(e) {
   	e.preventDefault();

		$.ajax({
		   type: "POST",
		   url: "login.php",
		   data: {
            username: $("#username").val(),
            password: $("#password").val()
         },
		   success: function(response) {
			   if (response == 'true') {
			   	 // Login successful, you can redirect or perform other actions
		         $("#login_form").fadeOut("normal");
				 setTimeout('window.location.href = "welcome.php";',1000);
		      } else {
		      	// Login failed, show error message
		    	 $("#error-message").addClass("alert-danger");
		         $("#error-message").text("Invalid username or password. Please try again.");
		         $("#error-message").show();
		         $('#login_form').find('input').val('')
		      }
		   },
		   error: function(xhr, status, error) {
              // Handle AJAX error here
     	   }
		});
		return false;
    });
});

Processing login at server side(login.php) 

Dive into the PHP code within the login.php file, which validates user login credentials on the server side. This step is crucial for security and data integrity. Create a file called login.php and add below code:

<?php
session_start();
include_once("connection.php");

$username = $_POST['username'];
$password = md5($_POST['password']);

// Fetch data from database
$sql   = "SELECT * FROM users WHERE username=:username and password=:password";
$query = $conn->prepare($sql);
$query->bindParam(':username', $username, PDO::PARAM_STR);
$query->bindParam(':password', $password, PDO::PARAM_STR);
$query->execute();
$result = $query->fetchAll(PDO::FETCH_OBJ);

if ($query->rowCount() > 0) {
	$_SESSION['username'] = $_POST['username'];
	echo 'true';
} else {
	echo 'false';
}
?>


After successful login, user will be redirected to the given page URL.
 

Welcome Page, After Successful Login (welcome.php)

After successful login, users are redirected to the welcome.php page. This page provides a warm welcome and can display personalized information to enhance user experience. Create a file called welcome.php and add below code:

<!DOCTYPE html>
<html lang="en">
<head>
<meta content="text/html; charset=utf-8" />
<title>Welcome Page</title>
<?php
session_start();
$username = $_SESSION['username'];
// Validating session
if (strlen($username)==0) {
	header('location:index.php');
} else { ?>
	<!DOCTYPE html>
	<html lang="en">
		<head>
		    <meta charset="UTF-8">
		    <meta name="viewport" content="width=device-width, initial-scale=1.0">
			<title>Welcome Page</title>
		</head>
		<body>
			<h1>Welcome Page</h1>
			<h3>Hello: <?php echo $username; ?></h3>
			<a href="logout.php">Logout</a>
		</body>
	</html>
<?php } ?>

Logout functionality(logout.php)

The logout.php file contains the logic for securely ending user sessions. This feature protects user privacy and ensures a smooth logout experience. Create a file called logout.php and add below code:

<?php
session_start();
session_destroy();
header('Location: index.php');
?>

 

Ketan Patel

As a backend and ecommerce developer, I have extensive experience in implementing robust and scalable solutions for ecommerce websites and applications. I have a deep understanding of server-side technologies and have worked with various programming languages. I have experience in integrating with payment gateways, and other third-party services.