Categories
PHP

Login with ajax and jQuery

This is a simple login page that use AJAX to create a user-friendly application.

Creating the Database Table

Execute SQL Dump file

-- phpMyAdmin SQL Dump
-- version 4.8.5
-- https://www.phpmyadmin.net/
--
-- Host: 127.0.0.1
-- Generation Time: Apr 13, 2020 at 12:00 PM
-- Server version: 10.1.38-MariaDB
-- PHP Version: 7.1.27

SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET AUTOCOMMIT = 0;
START TRANSACTION;
SET time_zone = "+00:00";


/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;

--
-- Database: `db_login`
--

-- --------------------------------------------------------

--
-- Table structure for table `tbl_users`
--

CREATE TABLE `tbl_users` (
  `user_id` int(11) NOT NULL,
  `email` varchar(100) NOT NULL,
  `password` varchar(100) NOT NULL,
  `isadmin` varchar(10) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Dumping data for table `tbl_users`
--

INSERT INTO `tbl_users` (`user_id`, `email`, `password`, `isadmin`) VALUES
(1, 'gr@gmail.com', 'admin', '1'),
(2, 'dddd', 'dsadasdddd', ''),
(3, 'ddd', 'ddd', '');

--
-- Indexes for dumped tables
--

--
-- Indexes for table `tbl_users`
--
ALTER TABLE `tbl_users`
  ADD PRIMARY KEY (`user_id`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `tbl_users`
--
ALTER TABLE `tbl_users`
  MODIFY `user_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=4;
COMMIT;

/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;

Creating the Connection File

After creating the table, we need to setup your database connection copy and paste the code below in order to connect to the MySQL database server. Let’s create and name it to “db_conn.php” and put the following code inside it.

<?php 
session_start();

$conn=mysqli_connect("localhost", "root", "", "db_login");

if(!$conn){
    die("Error: Failed To Connect Database!");
}
?>

Creating Login Page

First we will prevent user not to redirecting to home page if they are not logging in. We’ve two input box username and password for entering value and we can use AJAX for the submit button with jQuery. We can also use bootstrap for enhancing layout design and Izitoast for awesome looking popups Notification.

<?php
include "db_con.php";

if(isset($_SESSION['USERNAME'])) {
     header("Location: home.php"); // redirects them to homepage
     exit;
}

?>

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Proghubsterzeak</title>
  <link rel="stylesheet" href="./assets/bootstrap/css/bootstrap.min.css">
  <link rel="stylesheet" href="./assets/izitoast/dist/css/iziToast.min.css">
  <style>
  footer {
    position: absolute;
    width: 100%;
    bottom: 0;
  }
  </style>
</head>

<body class="login" style="height: 100vh;">
  <header>
    <nav class="navbar navbar-light bg-light">
      <span class="navbar-text">
        <a href="https://proghubsterzeak.com/"> https://proghubsterzeak.com</a>
      </span>
    </nav>
  </header>
  <main class="py-5">
    <section>
      <div class="col-lg-4 col-md-4 mx-auto mt-5">
        <form id="loginform" method="post">
          <div class="form-group">
            <label for="my-username">Username</label>
            <input id="username" class="form-control" type="text" name="username">
          </div>
          <div class="form-group">
            <label for="my-password">Username</label>
            <input id="password" class="form-control" type="password" name="password">
          </div>
          <button type="submit" class="btn btn-primary btn-block">LOGIN</button>
        </form>
      </div>
    </section>
  </main>
  <footer class="text-center py-2 bg-light">
    © 2020 Your Site
  </footer>
  <script src="./assets/jquery/jquery.min.js"></script>
  <script src="./assets/izitoast/dist/js/iziToast.min.js"></script>
  <script src="./assets/js/custom.js"></script>
</body>

</html>

Creating jQuery AJAX

AJAX will send request it will pass entered username and password as data. If the user entered valid password and username the response is equal to “success” and redirect to home.php page otherwise show an error message notification.

$(document).on('submit', '#loginform', function (event) {
  event.preventDefault();

  var username = $("#username").val();
  var password = $("#password").val();
  if (username != "" && password != "") {
    $.ajax({
      url: 'login.php',
      type: 'POST',
      data: {
        do_login: "login",
        username: username,
        password: password,
      },
      success: function (response) {

        if (response == "success") {
          iziToast.success({
            title: 'Success',
            message: 'Successfully Login',
            pauseOnHover: true,
            position: 'topRight',
            animateInside: true
          });

          window.location.href = "home.php";
        }
        else {
          iziToast.error({
            title: 'Error',
            message: 'Invalid Email or Password',
            pauseOnHover: true,
            position: 'topRight',
            animateInside: true
          });
        }
      }
    });

  } else {
    iziToast.info({
      title: 'Info',
      message: 'Please Fill All The Details',
      pauseOnHover: true,
      position: 'topRight',
      animateInside: true,
    });
  }

  return false;
});

Check if the users exists in the database table

<?php
  require_once 'db_con.php';
  
  if (isset($_POST['do_login'])){
    $email = $_POST['username'];
    $password = $_POST['password'];

    $query = mysqli_query($conn,"SELECT * FROM `tbl_users` WHERE `email` = '$email' && `password` = '$password'");
    $row = mysqli_num_rows($query);
    $fetch = mysqli_fetch_array($query);

  if($row > 0){
    $uname = $row['email'];
    $_SESSION['USERNAME'] = $uname;
    echo "success";
  }else{
    echo "failed";
  }
  
  }
?>

Create home.php and we’ll prevent user from coming back to login if they are already logged in. Logout button to end user’s session.

<?php 
include('db_con.php');

//Check whether the session variable SESS_MEMBER_ID is present or not
if (!isset($_SESSION['USERNAME']) || (trim($_SESSION['USERNAME']) == '')) {
    header("location: index.php");
    exit();
}

// logout
if(isset($_POST['logout'])){
    session_destroy();
    header('Location: index.php');
}
 ?>

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Proghubsterzeak</title>
  <link rel="stylesheet" href="./assets/bootstrap/css/bootstrap.min.css">
  <style>
  footer {
    position: absolute;
    width: 100%;
    bottom: 0;
  }
  </style>
</head>

<body>
  <header>
    <nav class="navbar navbar-light bg-light"><span class="navbar-text">
        <a href="https://proghubsterzeak.com/">https://proghubsterzeak.com</a>
      </span></nav>
  </header>
  <main class="py-5">
    <section>
      <div class="col-lg-4 col-md-4 mx-auto mt-5 text-center">
        <h3>Welcome: <?php echo  $_SESSION['USERNAME']; ?> </h3>
        <p class="text-center">Congratulations ! You've been logged in successfully</p>
        <form action="" method="post">
          <button name="logout" type="submit" class="mt-5 btn btn-primary btn-block">LOGOUT</button>
        </form>
      </div>
    </section>
  </main>
  <footer class="text-center py-2 bg-light">© 2020 Your Site </footer>
</body>

</html>

Download the complete source code. For more information about the system. You can contact me @ Email – larrydaveemol@gmail.com

Let me know what you need just leave a message/comment and I will do my very best to make that happen. I hope this codes will help you. Enjoy Coding!

Share this
  •  
  •  
  •  
  •  
  •  
  •  
  • 42
    Shares

Leave a Reply

Your email address will not be published. Required fields are marked *