首页 > 解决方案 > 检查表单是否已通过 php 中的 ajax 提交

问题描述

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

目前,我有一个检查表单是否已提交if statement的文件,问题是这永远不会评估为. 因此,我里面的代码永远不会运行。当通过 发送请求时,事件会被调用,而不会在 php 文件内部评估为 true。phpif statementtruephpif statementajax.onloadif 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);

标签: javascriptphp

解决方案


无法保证知道表单是通过 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
}

这里有几个链接可以查看:


推荐阅读