How to Restrict User Access on the Website with jQuery AJAX

Enable disable functionality gives the administrator more control on the site.

The administrator can directly control the users from its dashboard by either restrict access to some area of the site or enable disable the user.

This is very efficient when there are multiple types of the user exists on the site e.g. admin, student, professor, etc.

In this tutorial, I am using jQuery AJAX for this and creating an extra field on the MySQL table.

How to Restrict User Access on the Website with jQuery AJAX


Contents

  1. Table structure
  2. Configuration
  3. HTML & PHP
  4. CSS
  5. PHP
  6. jQuery
  7. Conclusion

 


 

1. Table structure

Create users table.

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

 

2. Configuration

Create a config.php for database connection.

Completed Code

<?php
session_start();
$host = "localhost"; /* Host name */
$user = "root"; /* User */
$password = ""; /* Password */
$dbname = "tutorial"; /* Database name */

$con = mysqli_connect($host, $user, $password,$dbname);
// Check connection
if (!$con) {
 die("Connection failed: " . mysqli_connect_error());
}

 

3. HTML & PHP

Creating two files – index.php and home.php.

index.php

Create a login form which contains two text elements and a submit button.

List all records from users table in <table>. For enable/disable the user added a <button class='active'> and use the username to define its id.

Here, set the button text according to the current $active value.

active = 0 – disable

active = 1 – enable

If the user is disabled (active=0) then assign "Enable" to $activeText and if it is enabled (active=1) then assign "Disable" to $activeText.

Completed Code

<?php 
include "config.php";
?>
<div class="container">

  <!-- Login Form -->
  <div id="div_login">
    <h1>Login</h1>
    <div id="message"></div>
    <div>
      <input type="text" class="textbox" id="txt_uname" name="txt_uname" placeholder="Username" />
    </div>
    <div>
      <input type="password" class="textbox" id="txt_pwd" name="txt_pwd" placeholder="Password"/>
    </div>
    <div>
      <input type="button" value="Submit" name="but_submit" id="but_submit" />
    </div>
  </div>

  <!-- Users List -->
  <h2 style='margin-top: 50px;'>Users List</h2>
  <table border='1' style='border-collapse: collapse;'>
    <tr>
     <th>S.no</th>
     <th>Username</th>
     <th>Name</th>
     <th>&nbsp;</th>
    </tr>
   <?php
   $fetchUsers = mysqli_query($con,"SELECT * FROM users");
   $sno = 1;
   while($row = mysqli_fetch_assoc($fetchUsers)){
     $id = $row['id'];
     $username = $row['username'];
     $name = $row['name'];
     $active = $row['active'];

     $activeText = "";
     if($active == 0){
       $activeText = "Enable";
     }else{
       $activeText = "Disable";
     }

     $enableDisableButton = "<button class='active' id='active_".$username."'>".$activeText."</button>";

     echo "<tr>";
     echo "<td>".$sno."</td>";
     echo "<td>".$username."</td>";
     echo "<td>".$name."</td>";
     echo "<td>".$enableDisableButton."</td>";
     echo "</tr>";

     $sno ++;
   }
   ?>
  </table>
</div>

home.php

Create home.php file. This file is called on successful login attempt.

Completed Code

<?php
include "config.php";

// Check user login or not
if(!isset($_SESSION['uname'])){
 header('Location: index.php');
}

// logout
if(isset($_POST['but_logout'])){
 session_destroy();
 header('Location: index.php');
}
?>
<!doctype html>
<html>
 <head>
 <title>Login page with jQuery and AJAX</title>
 </head>
 <body>
 <h1>Homepage</h1>
 <form method='post' action="">
 <input type="submit" value="Logout" name="but_logout">
 </form>
 </body>
</html>

 

4. CSS

/* Container */
.container{
 width:40%;
 margin:0 auto;
}

/* Login */
#div_login{
 border: 1px solid gray;
 border-radius: 3px;
 width: 470px;
 height: 270px;
 box-shadow: 0px 2px 2px 0px gray;
 margin: 0 auto;
}

#div_login h1{
 margin-top: 0px;
 font-weight: normal;
 padding: 10px;
 background-color: cornflowerblue;
 color: white;
 font-family: sans-serif;
}

#div_login div{
 clear: both;
 margin-top: 10px;
 padding: 5px;
}

#div_login .textbox{
 width: 96%;
 padding: 7px;
}

#div_login input[type=submit]{
 padding: 7px;
 width: 100px;
 background-color: lightseagreen;
 border: 0px;
 color: white;
}

#message{
 width:100%;
 text-align:center;
 color:red;
}

 

5. PHP

Create a new ajaxfile.php file.

Creating two services –

  1. Enable/Disable user
  2. Login User

Enable/Disable user

If $request value equals to 1 then store the POST active and username values.

Set the $return_val value according to the $active. If $active==0 then assign "Enable" otherwise "Disable".

Execute update query where pass the new active value and return $return_val.

Login User

If $request value equals to 2 then store the username and password values.

Here, while check the username and password in users table also pass active=1 in WHERE clause to check is active or not.

Set the $_SESSION['uname'] if record found.

Completed Code

<?php
include "config.php";

$request = $_POST['request'];

// Enable/Disable user
if($request == 1){
  $active = $_POST['active'];
  $username = $_POST['username'];

  $return_val = "";
  if($active == 0){
    $return_val = "Enable";
  }else{
    $return_val = "Disable";
  }

  // Update active value
  $sql = "UPDATE users SET active=".$active." WHERE username='".$username."'";
  mysqli_query($con,$sql);

  echo $return_val;
  exit;
}

// Login user
if($request == 2){
  $uname = $_POST['username'];
  $password = $_POST['password'];

  if ($uname != "" && $password != ""){

    $sql_query = "SELECT count(*) as cntUser FROM users WHERE username='".$uname."' AND password='".$password."' AND active=1";
    $result = mysqli_query($con,$sql_query);
    $row = mysqli_fetch_array($result);

    $count = $row['cntUser'];

    if($count > 0){
       $_SESSION['uname'] = $uname;
       echo 1;
    }else{
       echo 0;
    }

  }
  exit;
}

 

6. jQuery

Defined two event handlers –

  1. Enable/Disable User
  2. Login User

Enable/Disable User

Bind click event in active class. When the <button class='active'> gets clicked then split the id to get the username and button text.

If text == "Enable" then assign 1 to action otherwise 0.

Send an AJAX request where pass the {username: username, active: active, request: 1} as data. On the successful callback change button text with the response.

Login User

Get the input username and password values.

Send an AJAX request where pass {username: username,password: password,request:2} as data.

On the successful callback if the response is 1 then redirect page to home.php otherwise, show the "Invalid username and password" message.

Completed Code

$(document).ready(function(){

  // Enable/Disable user
  $('.active').click(function(){
    var id = this.id;
    var split_id = id.split("_");
    var username = split_id[1];

    var activeText = $(this).text();

    // Get active state
    var active = 0;
    if(activeText == "Enable"){
      active = 1;
    }else{
      active = 0;
    }

    // AJAX request
    $.ajax({
      url: 'checkUser.php',
      type: 'post',
      data: {username: username,active: active,request: 1},
      success: function(response){
        $("#"+id).html(response);
      }
    });
  });

  // User Login
  $("#but_submit").click(function(){
    var username = $("#txt_uname").val().trim();
    var password = $("#txt_pwd").val().trim();

    if( username != "" && password != "" ){
      $.ajax({
        url:'checkUser.php',
        type:'post',
        data:{username:username,password:password, request: 2},
        success:function(response){
          var msg = "";
          if(response == 1){
             window.location = "home.php";
          }else{
             msg = "Invalid username and password!";
          }
          $("#message").html(msg);
        }
      });
    }
  });

});

 

7. Conclusion

In the demonstration, I used the enable disable actions to restrict the user from login on the site but you can use it in any other area within your site where you want to control the user access.

If you like this post then don’t forget to share.

Related Post

Spread the love

Be First to Comment

Leave a Reply

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