简体   繁体   English

表单提交,即使 AJAX 表单检查返回 false

[英]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.我遇到的问题是来自 AJAX 调用的响应。 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.另外,在AJAX调用之前进行两次检查(用户是否填写了密码输入字段或用户名是否有效)时,代码完美运行。 It returns an error message and returns the false boolean value, preventing the form from submitting.它返回一条错误消息并返回 false 布尔值,从而阻止表单提交。 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?为什么表单仍在提交,即使我返回 false? I've checked the JavaScript console, there are no errors.我检查了 JavaScript 控制台,没有错误。 I've also tried inverting the if statement, checking if ajax.responseText === "true" , to the same result.我还尝试反转if语句,检查ajax.responseText === "true"是否为相同的结果。 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).我尝试在ajax.onreadystatechange调用下方添加 return false ,但这只会阻止表单提交(无论来自服务器的响应如何)。

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:这是js函数:

// 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 :这是处理AJAXPHP代码:

// 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.! :)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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