检查表单是否已通过php中的ajax提交

时间:2018-05-15 10:45:59

标签: javascript php

我有一个登录表单,使用javascript验证,然后发送到php文件进行进一步处理。表格通过ajax提交。

目前,我在if statement文件中有php,用于检查表单是否已提交,问题是此if statement永远不会评估为true。因此,我的php内的if statement代码永远不会运行。当通过ajax发送请求时,.onload事件在php文件中调用为if statement时调用为无效。

问题

表单通过php提交到ajax文件后,如何在php文件中检测到该表单是通过javascript提交的。

这是我的PHP代码

<?php

    require 'DbConnection.php';

    // if form is submitted
    if(isset($_POST['login-btn'])) {
        $username = $_POST['username-field'];
        $password = $_POST['password-field'];
        echo '<script>alert(\'form submitted\')</script>';
        verifyLoginCredentials($username, $password);
    } else {
        echo '<script>alert(\'form not submitted\')</script>';
    }

    // verify admin login credentials
    function verifyLoginCredentials($username, $password) {
        global $dbConnect;
        $query = 'SELECT full_name, username, password FROM admins WHERE username = ?';
        $statement = $dbConnect->prepare($query);

        if($statement) {
            $statement->bind_param('s', $username);
            $statement->execute();
            $resultSet = $statement->get_result();

            // since there will be only one row returned at max, no need of a loop
            $row = $resultSet->fetch_assoc();

            if($row != null) {
                $adminFullName = $row['full_name'];
                $adminUsername = $row['username'];
                $adminPassword = $row['password'];

                // if username/password is correct start session and store
                // username, password, full name in the session
                if($username === $adminUsername && password_verify($password, $adminPassword)) {
                    session_start();
                    $_SESSION['current_admin_fullname'] = $adminFullName;
                    $_SESSION['current_admin_username'] = $adminUsername;
                    $_SESSION['current_admin_password'] = $adminPassword;
                }
                else { // if username/password combination is incorrect
                    echo 'Incorrect Username/Password Combination';
                }
            } else { // if username doesn't exists in the database
                echo 'Entered username isn\'t registered';
            }
        } else {
            echo 'Error while preparing sql query';
        }
    }

?>

这里是相关的javascript代码

let loginForm = document.querySelector('.login-form');
let usernameField = document.getElementById('username-field');
let passwordField = document.getElementById('password-field');

// submit login form to server using ajax
function ajaxFormSubmit() {
    'use strict';
    let ajaxRequest = new XMLHttpRequest();
    let url = 'admin login.php';

    // login form submitted on server successfully
    ajaxRequest.onload = function () {
        if (ajaxRequest.readyState === 4 && ajaxRequest.status === 200) {
            console.log(ajaxRequest.responseText);
            displayInfoMessage(ajaxRequest.responseText, 'success');
        }
    };

    // error while login form submission on server
    ajaxRequest.onerror = function () {
        if (ajaxRequest.status !== 200) {
            console.log(ajaxRequest.responseText);
            displayInfoMessage(ajaxRequest.responseText, 'error');
        }
    };

    ajaxRequest.open('POST', url, true);
    ajaxRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    ajaxRequest.send(new FormData(loginForm));
}

function validateForm(e) {
    'use strict';

    // prevent form submission
    e.preventDefault();

    if (anyEmptyField()) {
        displayInfoMessage('Please fill all the empty fields', 'error');
        highLightEmptyFields();
        //return false;
        return;
    }

    // check if username is in right format
    if (!(regexTester(/^[A-Za-z0-9_]+$/g, usernameField.value))) {
        displayInfoMessage('Username not valid', 'error');
        highLightTextField(usernameField);
        //return false;
        return;
    }

    // check if username is atleast 3 characters long
    if (usernameField.value.length < 3) {
        displayInfoMessage('Username should contain atleast 3 characters', 'error');
        highLightTextField(usernameField);
        //return false;
        return;
    }

    // check if password is in right format
    if (!(regexTester(/^[A-Za-z0-9_]+$/g, passwordField.value))) {
        displayInfoMessage('Password not valid', 'error');
        highLightTextField(passwordField);
        //return false;
        return;
    }

    // check if password is atleast 6 characters long
    if (passwordField.value.length < 6) {
        displayInfoMessage('Password should contain atleast 6 characters', 'error');
        highLightTextField(passwordField);
        //return false;
        return;
    }

    //return true;
    // submit form information to server via ajax
    ajaxFormSubmit();
}

// add submit event listener on login form
loginForm.addEventListener('submit', validateForm);

1 个答案:

答案 0 :(得分:1)

无法保证知道该表单是通过ajax提交的。

通常这是通过标题完成的,在我们的案例中HTTP_X_REQUESTED_WITH可以通过全局$_SERVER变量检索。

请注意,标题很容易被欺骗。

您可以这样检查:

if(isset($_SERVER['HTTP_X_REQUESTED_WITH']) && !empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest')
{
    // code here
}

以下是一些链接: