javascript - 检查表单是否已通过 php 中的 ajax 提交
问题描述
我有一个登录表单,使用该表单进行验证javascript
,然后发送到php
文件进行进一步处理。表格通过 提交ajax
。
目前,我有一个检查表单是否已提交if statement
的文件,问题是这永远不会评估为. 因此,我里面的代码永远不会运行。当通过 发送请求时,事件会被调用,而不会在 php 文件内部评估为 true。php
if statement
true
php
if statement
ajax
.onload
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);
解决方案
无法保证知道表单是通过 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
}
这里有几个链接可以查看:
推荐阅读
- angularjs - xcode 上的 sqlite 搬运工“plugin_not_installed”
- angular - SELECT 在 Angular2/4 和 SAFARI 中无法正常工作
- android - 删除/删除特定缓存
- c# - 在选中该行的复选框时,绑定在“ OnCheckedChange”事件上的GridView内部的dropdownlist
- reactjs - 通过 Map 内的对象映射
- solr - Apachesolr 搜索结果排序
- cassandra - cassandra 如何通过添加节点来提高性能?
- asp.net-mvc-5 - SwaggerRequestExample 属性在 ASP.NET MVC 5 (.NET Framework 4.5.2) 中不起作用
- typescript - TypeScript:从等待的 Promise 中解构数组并在运行时编译并崩溃
- java - 在春季数据 jpa 中禁用自动更新