Checking login status using php and JQuery AJAX

Hi,
I have a modal log in system:

<!--Login Modal-->
<div class="modal fade" id="exampleModal2" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
   <div class="modal-dialog">
      <div class="modal-content">
         <div class="modal-header">
            <h5 class="modal-title" id="exampleModalLabel">Login</h5>
            <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
         </div>
         <div class="modal-body">
            <form method="POST">
               <div class="mb-3">
                  <label for="exampleInputText1" class="form-label">User name:</label>
                  <input type="text" name="username" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp">
               </div>
               <div class="mb-3">
                  <label for="exampleInputPassword1" class="form-label">Password:</label>
                  <input type="password" name="pass" class="form-control" id="exampleInputPassword1">
               </div>
               <div class="mb-3 form-check">
                  <input type="checkbox" class="form-check-input" id="exampleCheck1">
                  <label class="form-check-label" for="exampleCheck1">Check me out</label>
               </div>
               <div class="modal-footer">
                  <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                  <button type="button" id="btn_login" name="btn_login" class="btn btn-primary">Login</button>
               </div>
            </form>
            <div class="alert alert-danger" id="loginStatus" role="alert">
               Invalid username or password!
            </div>
         </div>
      </div>
   </div>
</div>
<!--end of login modal-->

I use combination of php and JQuery AJAX for checking login status:

  <script>
   $('#loginStatus').hide();
</script>
<script>
   $(document).ready(function() {
       $('#btn_login').click(function() {
           var username = $('#uname').val();
           var password = $('#pass').val();
           if (username != '' && password != '') {
               $.ajax({
                   url: "../app/model/login.php",
                   method = "POST",
                   data: {
                       username: user,
                       password: pass
                   },
                   success: function(data) {
                       if (data == 'No') {
                           $('#loginStatus').show(1000);
                       } else {
                           $('#exampleModal2').hide();
                           location.reload();
                       }
                   }
               });
           } else {
               $('#loginStatus').show();
           }
       });
   });
</script>

login.php:

<?php

session_start();

class User

{

    public function CheckUser()

    {

        require "../app/core/database.php";

        if (isset($_POST['user']) && isset($_POST['pass'])) {

            $user = $_POST['user'];

            $pass = $_POST['pass'];

            $data = $user;

            //Create a template

            $sql = "SELECT * FROM users WHERE username =?;";

            //Create a prepared statement

            $stmt = mysqli_stmt_init($connection);

            //Prepare the prepared statement

            if (!mysqli_stmt_prepare($stmt, $sql)) {

                echo "Statement failed";

                exit();

            } else {

                //Binding parameters to the placeholder

                mysqli_stmt_bind_param($stmt, "s", $data);

                //Run parameters inside database

                mysqli_stmt_execute($stmt);

                $log_result = mysqli_stmt_get_result($stmt);

                $count = mysqli_num_rows($log_result);

            }

            //to prevent sql injection

            if ($count == 1) {

                $row = mysqli_fetch_assoc($log_result);

                $hash = $row['password'];

                $hashed_pass = password_verify($pass, $hash);

                if ($hashed_pass == true) {

                    echo "Yes";

                    $_SESSION['loggedin'] = true;

                    $_SESSION['username'] = $user;

                    $_SESSION['is_admin'] = $row['admin'];

                    header("Location: ../home/index");

                } else {

                    $_SESSION['loggedin'] = false;

                }

            } else {

                echo "No";

            }

        }

    }

}

I want to show “Invalid username or password!” message in the same modal if the login failed.
please help me.
When I press Login button, nothing happens.

First of all you shouldn’t be sending a password via Ajax and JavaScript if you are just checking to see if password is valid to your requirements.

Second this is how I check to see if a username is already “taken” (Written in Vanilla JS).

Username is unavailable!
    <div class="password1">
        <label for="passwordBox">Password</label>
        <input class="passwordBox1" id="passwordBox" type="password" name="user[hashed_password]" value=""
               tabindex="6" required>
        <label for="passwordVisibility">Show Passwords (private computer)</label>
        <input class="passwordBtn1" id="passwordVisibility" type="checkbox" tabindex="7">
    </div>

    <div class="password2">
        <label for="redoPassword">ReEnter Password</label>
        <input class="passwordBox2" id="redoPassword" type="password" name="user[redo]" value="" tabindex="8"
               required>
    </div>

    <div class="submitForm">
        <button class="submitBtn" id="submitForm" type="submit" name="submit" value="enter" tabindex="10">Submit</button>
    </div>


</form>

The JavaScript:

/* Success function utilizing FETCH username */
const sendUISuccess = function (result) {
    //console.log('Result', result);

    if (result.check) {
        text_username.style.color = "darkgreen";
        error.style.display = 'inline-block';
        submitBtn.style.display = "none";
    } else {
        text_username.style.color = "#ffffff"
        error.style.display = 'none';
        submitBtn.style.display = "inline-block";
    }

};

/* If Database Table fails to update data in mysql table */
const sendUIError = function (error) {
    console.log("Database Table did not load", error);
};

const handleSaveErrors = function (response) {
    if (!response.ok) {
        throw (response.status + ' : ' + response.statusText);
    }
    return response.json();
};

const saveRequest = (sendUrl, succeed, fail) => {
    //console.log('username stringify', JSON.stringify(send))
    fetch(sendUrl, {
        method: 'POST', // or 'PUT'
        body: JSON.stringify(send)

    })
        .then((response) => handleSaveErrors(response))
        .then((data) => succeed(data))
        .catch((error) => fail(error));
};

username.addEventListener('input', () => {
    //console.log(check);
    send.check = username.value;
    //console.log('username', send)
    saveRequest(url, sendUISuccess, sendUIError);
} );

the PHP:

<?php
require_once "../assets/config/config.php";
require_once "../vendor/autoload.php";

use PhotoTech\Validation;

/*
 * The below must be used in order for the json to be decoded properly.
 */
$data = json_decode(file_get_contents('php://input'), true);

$result = Validation::usernameCheck($data['check']);

output($result);




function errorOutput($output, $code = 500) {
    http_response_code($code);
    echo json_encode($output);
}


/*
 * After converting data array to JSON send back to javascript using
 * this function.
 */
function output($output) {
    http_response_code(200);
    echo json_encode($output);
}

and finally the Class that handles it:

public static function usernameCheck($username): array
{
    $query = "SELECT username FROM " . static::$table ." WHERE username = :username";
    $stmt = Database::pdo()->prepare($query);
    $stmt->bindParam(':username', $username);
    $stmt->execute();
    if ($stmt->fetch(PDO::FETCH_ASSOC)) {
        $data['check'] = true;
        return $data;
    }
    $data['check'] = false;
    return $data;
}

This is basically a courtesy for the user that is registering as I also check the username for a duplicate when actually write to a database.

The password requirement can all be done in Javascript.

Now with login I personally would not tell the user the username or password is invalid as most people know their credentials. You might have a button that says “Forgot your username or password credentials? Click Here” or something like that.

Sorry I was half asleep when I read your post :rofl:, but decided to leave the top portion in as maybe it can be modified to simply check the login status though I still wouldn’t send invalid messages to the user as all that is going to do is give a hacker some information he or she doesn’t need to know.

The first problem is that, the IF statement in JQuery does not work, meaning, when I leave the user/pass fields empty and press login button, nothing happens.

None of the jquery code is working because you have a syntax error in it. You need to use the developer console in your browser to find client-side errors. You should be getting an error like - Uncaught SyntaxError: Invalid shorthand property initializer, for the following line of code -

method = "POST",

The correct syntax, found in the documentation and in any jquery .ajax example, is -

method: "POST",

After you correct that, you will be getting errors due to the following lines of code -

           var username = $('#uname').val();
           var password = $('#pass').val();

                       username: user,
                       password: pass

There are no uname and pass ids in the markup and if there were you are assigning the values to usrename and password, so, user and pass don’t exist at the 2nd two lines.

1 Like
Sponsor our Newsletter | Privacy Policy | Terms of Service