简体   繁体   中英

Form submitting, even when AJAX form check returns false

I have a really simple login form that I want to check if the credentials are right (so I don't have to reload a page if the credentials are wrong) before submitting the form.

The problem I'm running into is the response from the AJAX call. When the program decides that the user has supplied the correct credentials, this code works like a charm. In addition, when performing the two checks prior to the AJAX call (whether the user filled in the password input field or if the username is valid), the code works perfectly. It returns an error message and returns the false boolean value, preventing the form from submitting. But, when the response from the server comes back and it is found that the credentials are not correct, the error message displays, but the page also reloads (therein displaying an additional error message). Why is the form still submitting, even though I'm returning false? I've checked the JavaScript console, there are no errors. I've also tried inverting the if statement, checking if ajax.responseText === "true" , to the same result. I've tried adding a return false beneath the ajax.onreadystatechange call, but that just prevents the form from submitting at all (regardless of the response from the server).

Here is the form code:

<form method="POST" action="/afton/" onsubmit="return checkForm()">
    <label for="username">Username:</label>
    <input type='text' id='username' name='username' placeholder='Enter username...' required>
    <label for="password">Password:</label>
    <input type='password' id='password' name='password' placeholder='Enter password...' required>
    <div class="form-buttons">
        <button type='submit' name='action' id="loginButton" value='login'>Login</button>
        <button type='button' id='register'>Register</button>
    </div>
</form>

Here is the js function:

// Function that checks whether the user supplied correct credentials
function checkForm() {

// Get the password provided and the server message div on the page
    const messageBox = document.getElementById("server-message");
    const password = document.getElementById("password").value;

// If password is blank, return error message and return false
    if (password === "") {
        messageBox.innerHTML = "<p class='badMessage'>Please fill in the password!</p>"
        return false;
    }

// If the username input tag doesn't contain the 'goodBorder' class received upon validation of username, return error and false
    if (!usernameInput.classList.contains("goodBorder")) {
        messageBox.innerHTML = "<p class='badMessage'>Please provide a valid username!</p>"
        return false;
    }

// AJAX call that posts the info via JSON to check
    const ajax = new XMLHttpRequest();
    ajax.open("POST", "index.php?action=ajaxLogCheck", true);
    ajax.setRequestHeader("Content-type", "application/json");
    ajax.send(JSON.stringify({"username":usernameInput.value, "password":password}));

// Handles the AJAX response
    ajax.onreadystatechange = function () {
        if (ajax.readyState === 4 && ajax.status === 200) {
            if (ajax.responseText !== "true") {
                messageBox.innerHTML = ajax.responseText;
                return false;
            }
            return true
        }
    }
}

And here is the PHP code that handles the AJAX :

// Get posted JSON encoded data
    $data = json_decode(trim(file_get_contents("php://input")), true);

// Filter and sanitize the supplied username and password
    $username = filter_var($data['username'], FILTER_SANITIZE_STRING);
    $password = filter_var($data['password'], FILTER_SANITIZE_STRING);

// Get user data by the username and check the username against the password
    $userData = getClient($username);
    $hashCheck = password_verify($password, $userData['password']);

// Check response from the hashCheck and return the result
    if ($hashCheck) {
        echo "true";
        exit;
    }
    logAtt($username, $_SERVER['REMOTE_ADDR'], false, getBrowser($_SERVER['HTTP_USER_AGENT']));
    sleep(0.5);
    $rands = array("Sorry, the username and/or password doesn't match our database. Please try again.", "Sorry, we don't recognize those login credentials. Please try again.", "Sorry, that login was incorrect. Please try again.", "Incorrect, please try again");
    $randResult = array_rand(array_flip($rands));
    echo "<p class='badMessage'>$randResult</p>";
        // Just the point in AJAX function where you were returning True or
        // False...Just Assign RESULT = 0 for False and 
        // RESULT = 1 for True
        // .....SUppose You password matches so you were returning True..
        // Dont do that...Instead Just Assign RESULT = 0 in that place and 
        // and out of the ajax Block paste this 'return Boolean(RESULT)'
        // if RESULT = 0 then it will return False else it will return True
// Function that checks whether the user supplied correct credentials
function checkForm()
    {
        // Initialize a Variable Here Say RESULT
        var RESULT = 0;
        if (password === "") 
            {
                 RESULT = 0;
            }
        else if (!usernameInput.classList.contains("goodBorder")) 
            {
                messageBox.innerHTML = "<p class='badMessage'>Please provide a valid username!</p>"
                RESULT = 0;
            }
        // After this Put the ajax function and if you want to return False
        // then simply assign RESULT = 0 instead of 'return false' else assign
        // RESULT = 1 instead of 'return true'

        return Booelan(RESULT); 
        // THis line is main Part this is returned by checkForm() function
    }

// If I am still not clear, then I'll be happy to explain it on Google Meet.! :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM