ajax - 执行 php 脚本和数据验证时出错 - 如何解决?
Posted
技术标签:
【中文标题】ajax - 执行 php 脚本和数据验证时出错 - 如何解决?【英文标题】:ajax - Error with execution of php script and data validation - how to solve? 【发布时间】:2018-11-29 23:53:11 【问题描述】:我为我的网站制作了一个注册表单。然后,我创建了 php 脚本,它验证用户数据并将其插入数据库,它运行良好。然后,我尝试进行 AJAX 验证,它将在 html 元素上应用样式并在发生错误时显示错误消息。我遵循了一些教程,阅读了 Stack Overflow 的答案和解决方案,但由于某种原因,它不起作用。当我单击提交按钮时,没有任何反应。
这是我的代码:
HTML
<form id="signupForm" action="./includes/signup.script.php" method="POST">
<div id="emptyFields" class="inputErrorMessage">
<p>You must fill all fields!</p>
</div>
<div class="form-group">
<label for="formGroupExampleInput">First name</label>
<input id="firstName" type="text" name="firstName" class="form-control formFieldBO">
<div id="firstNameChar" class="inputErrorMessage">
<p>First name must contain letters only.</p>
</div>
<div id="firstNameLength" class="inputErrorMessage">
<p>First name must contain at least 2 characters.</p>
</div>
</div>
<div class="form-group">
<label for="formGroupExampleInput">Last name</label>
<input id="lastName" type="text" name="lastName" class="form-control formFieldBO">
<div id="lastNameChar" class="inputErrorMessage">
<p>Last name must contain letters only.</p>
</div>
<div id="lastNameLenght" class="inputErrorMessage">
<p>Last name must contain at least 2 characters.</p>
</div>
</div>
<div class="form-group">
<label for="formGroupExampleInput">E-mail</label>
<input id="email" type="email" name="email" class="form-control formFieldBO">
<div id="emailValid" class="inputErrorMessage">
<p>Please, enter e-mail in valid form.</p>
</div>
</div>
<div class="form-group">
<label for="formGroupExampleInput">Password</label>
<input id="password" type="password" name="password" class="form-control formFieldBO">
<div id="passwordChar" class="inputErrorMessage">
<p>Password must contain at least 6 characters.</p>
</div>
</div>
<div class="form-group">
<label for="formGroupExampleInput">Confirm Password</label>
<input id="confirmPassword" type="password" name="confirmPassword" class="form-control formFieldBO">
<div id="passwordConfirm" class="inputErrorMessage">
<p>Confirmed password does not match.</p>
</div>
</div>
<div class="form-group">
<label for="formGroupExampleInput">Country</label>
<select id="inputState" name="country" class="form-control formFieldBO">
<option value="" disabled selected>Select country</option>
<option value="AFG">Afghanistan</option>
</select>
<div id="countryChoose" class="inputErrorMessage">
<p>Please, choose your country.</p>
</div>
</div>
<div class="buttonBO">
<button type="submit" name="submit" class="btn btn-success">Submit</button>
</div>
</form>
jQuery 脚本
$(document).ready(function()
$("#signupForm").submit(function(event)
event.preventDefault();
/*
var firstName = $("#firstName").val();
var lastName = $("#lastName").val();
var email = $("#email").val();
var password = $("#password").val();
var confirmPassword = $("#confirmPassword").val();
var country = $("#inputState").val();
*/
var url = "includes/signup.script.php";
var formData = $(this).serialize();
$.ajax(
type: "POST",
url: url,
data: formData
);
);
);
PHP 和 JQuery
<?php
if (isset($_POST['submit']))
include_once "dbconn.script.php";
$firstName = mysqli_real_escape_string($conn, $_POST['firstName']);
$lastName = mysqli_real_escape_string($conn, $_POST['lastName']);
$email = mysqli_real_escape_string($conn, $_POST['email']);
$password = mysqli_real_escape_string($conn, $_POST['password']);
$confirmPassword = mysqli_real_escape_string($conn, $_POST['confirmPassword']);
$user_role = 1;
$country = mysqli_real_escape_string($conn, $_POST['country']);
$errorEmpty = false;
$errorFirstNameChar = false;
$errorFirstNameNo = false;
$errorLastNameChar = false;
$errorLastNameNo = false;
$errorEmail = false;
$errorPasswordChar = false;
$errorPasswordMatch = false;
$errorCountry = false;
// Error handlers
// Check for empty fields
if (empty($firstName) || empty($lastName) || empty($email) || empty($password) || empty($confirmPassword))
header("Location: ../registration.php?registration=empty");
$errorEmpty = true;
exit();
else
// Check if input FIRST NAME characters are valid
if (!preg_match("/^[a-zA-Z]*$/", $firstName))
header("Location: ../registration.php?registration=firstinvalidchar");
$errorFirstNameChar = true;
exit();
else
// Check if number of FIRST NAME characters is valid
if (strlen($firstName) < 2)
header("Location: ../registration.php?registration=invalid1");
$errorFirstNameNo = true;
exit();
else
// Check if input LAST NAME characters are valid
if (!preg_match("/^[a-zA-Z]*$/", $lastName))
header("Location: ../registration.php?registration=lastinvalidchar");
$errorLastNameChar = true;
exit();
else
// Check if number of LAST NAME characters is valid
if (strlen($lastName) < 2)
header("Location: ../registration.php?registration=invalid2");
$errorLastNameNo = true;
exit();
else
// Check if EMAIL is valid
if (!filter_var($email, FILTER_VALIDATE_EMAIL))
header("Location: ../registration.php?registration=invalidemail");
$errorEmail = true;
exit();
else
// PREPARED STATEMENT
// Create template
$sql = "SELECT e_mail FROM hieroglyphicus_users WHERE e_mail=?;";
// Create prepared statement
$stmt = mysqli_stmt_init($conn);
// Prepare the prepared statement
if (!mysqli_stmt_prepare($stmt, $sql))
echo "SQL statement failed!";
else
// Bind parameters to the placeholder
mysqli_stmt_bind_param($stmt, "s", $email);
// Run parameters inside database
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
$resultCheck = mysqli_num_rows($result);
if ($resultCheck > 0)
header("Location: ../registration.php?registration=userexists");
exit();
else
// Check if password number of characters is valid
if (strlen($password) < 6)
header("Location: ../registration.php?registration=invalidemaicharno");
$errorPasswordChar = true;
exit();
else
// Check if passwords match
if ($password != $confirmPassword)
header("Location: ../registration.php?registration=mismatchedpass");
$errorPasswordMatch = true;
exit();
else
if ($country == "")
header("Location: ../registration.php?registration=nocountry");
$errorCountry = true;
exit();
else
// Hashing passwords
$hashedPwd = password_hash($password, PASSWORD_DEFAULT);
// Insert a user into the database
// PREPARED STATEMENT
// Create template
$sql = "INSERT INTO hieroglyphicus_users (first_name, last_name, e_mail, user_pw, user_role, country)
VALUES (?, ?, ?, ?, ?, ?);";
// Create prepared statement
$stmt = mysqli_stmt_init($conn);
// Prepare the prepared statement
if (!mysqli_stmt_prepare($stmt, $sql))
echo "SQL statement failed!";
else
// Bind parameters to the placeholder
mysqli_stmt_bind_param($stmt, "ssssis", $firstName, $lastName, $email, $hashedPwd, $user_role, $country);
// Run parameters inside database
mysqli_stmt_execute($stmt);
header("Location: ../registration.php?registration=success");
exit();
else
header("Location: ../registration.php");
exit();
?>
<script>
$("#firstName, #lastName, #email, #password, #confirmPassword, #country").removeClass("formFieldBOError").addClass("formFieldBO");
$(".inputErrorMessage").hide();
var errorEmpty = "<?php echo $errorEmpty; ?>";
var errorFirstNameChar = "<?php echo $errorNameFirstChar; ?>";
var errorFirstNameNo = "<?php echo $errorFirstNameNo; ?>";
var errorLastNameChar = "<?php echo $errorNameLastChar; ?>";
var errorLastNameNo = "<?php echo $errorLastNameNo; ?>";
var errorEmail = "<?php echo $errorEmail; ?>";
var errorPasswordChar = "<?php echo $errorPasswordChar; ?>";
var errorPasswordMatch = "<?php echo $errorPasswordMatch; ?>";
var errorCountry = "<?php echo $errorCountry; ?>";
if (errorEmpty == true)
$("#emptyFields").show();
$("#signupForm :input:not(:button):not(:select)").removeClass("formFieldBO").addClass("formFieldBOError");
if (errorFirstNameChar == true)
$("#firstNameChar").show();
$("#firstName").removeClass("formFieldBO").addClass("formFieldBOError");
if (errorFirstNameNo == true)
$("#firstNameChar").show();
$("#firstName").removeClass("formFieldBO").addClass("formFieldBOError");
if (errorLastNameChar == true)
$("#lastNameChar").show();
$("#lastName").removeClass("formFieldBO").addClass("formFieldBOError");
if (errorLastNameNo == true)
$("#lastNameChar").show();
$("#lastName").removeClass("formFieldBO").addClass("formFieldBOError");
if (errorEmail == true)
$("#emailValid").show();
$("#email").removeClass("formFieldBO").addClass("formFieldBOError");
if (errorPasswordChar == true)
$("#passwordChar").show();
$("#password").removeClass("formFieldBO").addClass("formFieldBOError");
if (errorPasswordMatch == true)
$("#passwordConfirm").show();
$("#confirmPassword").removeClass("formFieldBO").addClass("formFieldBOError");
if (errorCountry == true)
$("#countryChoose").show();
$("#inputState").removeClass("formFieldBO").addClass("formFieldBOError");
if (errorEmpty == false && errorFirstNameChar == false && errorFirstNameNo == false && errorLastNameChar == false && errorLastNameNo == false && errorEmail == false && errorPasswordChar == false && errorPasswordMatch == false && errorCountry == false)
$("#firstName, #lastName, #email, #password, #confirmPassword, #country").val("");
</script>
我无法发现问题或错误。非常感谢任何帮助!
【问题讨论】:
你需要包含jquery validation plugin
jqueryvalidation.org ...而且你还需要validate
你的form
首先...看看这个小演示:jsfiddle.net/amwmedia/sw87W
当您按下提交时,您期望会发生什么?您阻止了默认操作,并且您没有执行任何操作或为您的 ajax 函数提供任何回调。
旁注:当你最终有 12 个嵌套的 if 时,代码设计中可能有问题。 (一个提示:在exit
之后不需要else
)
我猜你的误解是 header("...")
重定向。当您通过 ajax 调用 php 脚本时,它们不会将用户重定向到该位置。
(Hackerman) 我正在尝试制作自己的验证脚本。我试图不使用插件。 (Devon) 当我只使用 PHP 来验证函数时,这 12 个嵌套的“ifs”就像一个魅力,所以它们没有问题。我在一个教程中使用了这种方法。你能向我解释一下如何修改这个 Jquery 代码来实际完成这项工作吗?我应该改变什么? (Jeff) 我将尝试禁用此标头功能,并尝试在没有它的情况下运行代码。
【参考方案1】:
$("#signupForm").on('submit', function()
把所有的JQuery验证码放在这个函数下。
将按钮 type="submit" 更改为 input type="submit" 。
让我们看看这是否能解决你的问题。
【讨论】:
我改了还是不行。我发布的 PHP 和 JQuery 代码位于名为signup.script.php
的文件中,我使用 $.ajax
函数调用该文件。我应该使用$.post
而不是$.ajax
?
另外,我必须承认,在我看的教程中,那个家伙使用了$(someid).load(some.php, name: name, ...)
,但是他用这个确实会在下面的表单中显示各种错误消息,但我正在尝试使用另一种方法, 根据错误改变表单字段的样式和显示/隐藏html元素。
您的 ajax 函数没有接收回数据,该代码丢失。
放一个成功:以及接收数据并相应显示的函数以上是关于ajax - 执行 php 脚本和数据验证时出错 - 如何解决?的主要内容,如果未能解决你的问题,请参考以下文章