gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 20:30:53 25 4
gpt4 key购买 nike

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

目前,我在 php 文件中有一个 if 语句 检查表单是否已提交,问题是这个 if 语句 永远不会计算为。因此,我的 if 语句 中的 php 代码永远不会运行。当请求通过 ajax 发送时,.onload 事件被调用,而 php 文件中的 if 语句 评估为 true。

问题

一旦通过 ajax 将表单提交到 php 文件,我如何在 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);

最佳答案

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

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

请注意, header 很容易被欺骗。

你可以这样检查:

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

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

关于javascript - 检查表单是否已通过php中的ajax提交,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50348267/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com