所以我正在做的是带有一些验证的基本注册表单,我真的不知道它是否有效,因为我不知道如何在索引文件中很好地显示这些消息,而事实是我“我的目标是单页应用程序,而表单是从模式提交的,因此我不想在显示消息时刷新页面。
我知道它涉及到一些ajax,但是我不知道一种从php文件中获取这些错误消息并将其传递到javascript文件中的方法,例如,如果我将这些标头消息分配给一个变量,该如何处理?在整个文件中获取此变量,因为我也不想重复此验证并在javascript中设置变量,这可能会有一个更简单的答案,但是当我搜索每个教程时,它会在另一个页面中完全创建注册页面或具有php代码在我不想做的索引文件中,
<?php
include "../config/Database.php";
if (isset($_POST['submit'])) {
$firstname = htmlspecialchars(trim($_POST['firstname']));
$lastname = htmlspecialchars(trim($_POST['lastname']));
$email = htmlspecialchars(trim($_POST['email']));
$username = htmlspecialchars(trim($_POST['username']));
$pass = htmlspecialchars(trim($_POST['pass']));
if (empty($firstname) || empty($lastname) || empty($email) || empty($username) || empty($pass)) {
header("Location: ../index.php?signup=empty");
exit();
} else if (!preg_match('/^[a-zA-Z]*$/', $firstname) || !preg_match('/^[a-zA-Z]*$/', $lastname)){
header("Location: ../index.php?signup=char");
exit();
} elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
header("Location: ../index.php?signup=email");
exit();
} elseif (strlen($pass) < 8) {
header("Location: ../index.php?signup=pass8");
exit();
} elseif (!preg_match("#[0-9]+#", $pass)) {
header("Location: ../index.php?signup=pass");
exit();
} elseif (!preg_match("#[A-Z]+#", $pass)) {
header("Location: ../index.php?signup=pass");
exit();
} elseif (!preg_match("#[a-z]+#", $pass)) {
header("Location: ../index.php?signup=pass");
exit();
} elseif (!preg_match('/^[a-zA-Z0-9]{5,}$/', $username)) {
header("Location: ../index.php?signup=username");
exit();
} else {
header('Location: ../index.php?signup=success');
}
$sql = 'INSERT INTO users(firstname,lastname,email,uname,pass)
VALUES(:firstname,:lastname,:email,:uname,:pass)';
$stmt = $conn->prepare($sql);
$result = $stmt->execute([':firstname' => $firstname, ':lastname' => $lastname, ':email' => $email, ':uname' => $username, ':pass' => $pass]);
} else {
header("Location: ../index.php");
}
稍作编辑,这是HTML表单,以模式形式,基本上,您可以看到2个div 带有成功和错误消息类别,当我进行ajax调用时,我想相应地显示它们
<form action="inc/register.php" target="myIframe" method="POST">
<h4 class="black-text">Registration</h4>
<div id="msgError" class="msg msg-error z-depth-3 scale-transition" style="display:none"></div>
<div id="msgSuccess" class="msg msg-info z-depth-3 scale-transition" style="display:none"></div>
<div class="row">
<div class="input-field col s12">
<input placeholder="Firstname" id="firstname" type="text" name="firstname" class="validate">
<div id="firstname_error" class="val_error"></div>
</div>
</div>
<div class="row">
<div class="input-field col s12">
<input placeholder="Lastname" id="lastname" type="text" name="lastname" class="validate">
<div id="lastname_error" class="val_error"></div>
</div>
</div>
<div class="row">
<div class="input-field col s12">
<input placeholder="Email" id="email" type="text" name="email" class="validate">
<div id="email_error" class="val_error"></div>
</div>
</div>
<div class="row">
<div class="input-field col s12">
<input placeholder="Username" id="username" type="text" name="username" class="validate">
<div id="username_error" class="val_error"></div>
</div>
</div>
<div class="row">
<div class="input-field col s12">
<input placeholder="Password" id="password" type="password" name="pass" class="validate">
<div id="password_error" class="val_error"></div>
</div>
</div>
<button class="btn waves-effect waves-light" type="submit" onclick="return myFunction()" id="submit" name="submit">Register
</button>
<button class="btn modal-close waves-effect waves-light">Cancel
</button>
</form>
这是我尝试使用的ajax调用
$.ajax({
type: "POST",
url: "inc/register.php",
data: dataString,
cache: false,
success: function(html) {
msgSuccess.setAttribute('style', 'display: ""');
msgSuccess.innerHTML = "Signup Successful";
}
});
但是我不能真正显示与发生错误有关的错误
答案 0 :(得分:0)
正如我在前面的评论中提到的那样,您需要Json
才能实现目标。
我对您的PHP代码进行了一些其他调整,这些注释也得到了评论。
Json响应结构
{
"success": false,
"errors": [{
"id": "msg",
"msg": "Please correct the given mistakes"
}, {
"id": "firstname_error",
"msg": "Invalid email entered"
}, {
"id": "username_error",
"msg": "Username must be atleast 5 characters long & alphanumeric"
}]
}
或
{
"success": true,
"errors": []
}
要实现我们想要的功能,我们必须单独运行所有检查,然后通过Json
分配并返回其返回结果(可在JS / jQuery中使用)。
我们使用数组$data
来保存验证状态以及错误消息和应在其中显示元素的css标识符。
PHP代码:
<?php
include "../config/Database.php";
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
// Checks whether the request type is `POST` rather than check if a field named `submit` is available
// $data will be encoded as json and then returned by the script
$data = array(
'success' => false, // Flag whether everything was successful
'errors' => array() // Provide information regarding the error(s)
);
$firstname = htmlspecialchars(trim($_POST['firstname']));
$lastname = htmlspecialchars(trim($_POST['lastname']));
$email = htmlspecialchars(trim($_POST['email']));
$username = htmlspecialchars(trim($_POST['username']));
$pass = htmlspecialchars(trim($_POST['pass']));
/* We will use individual `if` for all checks below, because
`elseif` stops as soon as one of the conditions returns `true`
and skips the rest of the validation checks, but we need to tell
the user about all errors in one attempt and not one-by-one */
if (empty($firstname) || empty($lastname) || empty($email) || empty($username) || empty($pass)) {
$data['errors'][] = ['id'=>'msg', 'msg' => 'All fields are required'];
// `id` should carry the css id of error div attached to field where the error originated from
} else {
$data['errors'][] = ['id'=>'msg', 'msg' => 'Please correct the given mistakes'];
if (!preg_match('/^[a-zA-Z]*$/', $firstname) || !preg_match('/^[a-zA-Z]*$/', $lastname)){
$data['errors'][] = ['id'=>'firstname_error', 'msg' => 'Numbers and Symbols not allowed in name'];
}
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$data['errors'][] = ['id'=>'firstname_error', 'msg' => 'Invalid email entered'];
}
if (strlen($pass) < 8) {
$data['errors'][] = ['id'=>'firstname_error', 'msg' => 'Password must use 8 characters'];
}
if (!preg_match("/^[a-zA-Z0-9]+$/", $pass)) {
// I unified your password validation regex pattern
$data['errors'][] = ['id'=>'password_error', 'msg' => 'Password must be alphanumeric'];
}
if (!preg_match('/^[a-zA-Z0-9]{5,}$/', $username)) {
$data['errors'][] = ['id'=>'username_error', 'msg' => 'Username must be atleast 5 characters long & alphanumeric'];
}
}
// Execute only if there are no erros
if (empty($data['errors'])) {
// Validation complete without errors, do the required stuff here
$sql = 'INSERT INTO users (firstname,lastname,email,uname,pass) VALUES (:firstname,:lastname,:email,:uname,:pass)';
$stmt = $conn->prepare($sql);
$result = $stmt->execute([':firstname' => $firstname, ':lastname' => $lastname, ':email' => $email, ':uname' => $username, ':pass' => $pass]);
// Everything done, mark the registration as successful
$data['success'] = true;
}
// Return the data with a `json` mime type instead of html
header("Content-Type: application/json; charset=UTF-8");
echo json_encode((object)$data); // converts array into json
}
?>
jQuery Ajax代码:
$(".signupform").submit(function(event) {
event.preventDefault(); // prevent form submitting with page refresh here
$.ajax({
url: 'inc/register.php', // php script's location
type : "POST",
dataType : 'json', // data type
data: $(this).serialize(), // creates a URL encoded text string by serializing form values
success: function(data) {
//Check to see if the validation was successful
if (data.success) {
//Turn the response msg into a success alert
$('#msg').addClass('msg-info').text('Registration Complete');
$('#msg').show(); // removes display:none property
} else {
//There were some errors
//Turn the response alert into an error alert
$('#msg').addClass('msg-error');
// add `msg` to individual fields with there `id` in json
$.each(data.errors, function(){
$('#' + this.id).text(this.msg);
});
$('#msg').show();
}
}
});
});
您的html也需要稍作调整:
<form class="signupform" action="inc/register.php" method="POST">
<h4 class="black-text">Registration</h4>
<div id="msg" class="msg z-depth-3 scale-transition" style="display:none"></div>
<div class="row">
<div class="input-field col s12">
<input placeholder="Firstname" id="firstname" type="text" name="firstname" class="validate">
<div id="firstname_error" class="val_error"></div>
</div>
</div>
<div class="row">
<div class="input-field col s12">
<input placeholder="Lastname" id="lastname" type="text" name="lastname" class="validate">
<div id="lastname_error" class="val_error"></div>
</div>
</div>
<div class="row">
<div class="input-field col s12">
<input placeholder="Email" id="email" type="text" name="email" class="validate">
<div id="email_error" class="val_error"></div>
</div>
</div>
<div class="row">
<div class="input-field col s12">
<input placeholder="Username" id="username" type="text" name="username" class="validate">
<div id="username_error" class="val_error"></div>
</div>
</div>
<div class="row">
<div class="input-field col s12">
<input placeholder="Password" id="password" type="password" name="pass" class="validate">
<div id="password_error" class="val_error"></div>
</div>
</div>
<button class="btn waves-effect waves-light" type="submit" id="submit" name="submit">Register
</button>
<button class="btn modal-close waves-effect waves-light">Cancel
</button>
</form>