【发布时间】:2023-04-11 06:26:01
【问题描述】:
基本上,我正在验证注册表单并使用 ajax 调用 php 脚本来检查电子邮件地址是否已存在或查询是否执行。如果一个电子邮件地址已经存在(通过计数查询检查),我将向 ajax 函数回显一个错误(通过响应) - 但是它没有被读取。
我尝试研究类似的主题,但没有成功。
ajax
$.ajax({
type: 'POST',
url: 'signup-user.php',
dataType: 'text',
data: $('form').serialize(),
success: function(response) {
if(response == "error-email-exists"){
$('#errorMsg').html("An account is already assosciated with the email adress you entered.");
$('#errorMsg').hide().stop(true,true).fadeIn(600);
}else if(response == "success"){
window.location = "index.php";
}else{
$('#errorMsg').html(response);
$('#errorMsg').hide().stop(true,true).fadeIn(600);
}
}
});
php
<?php
session_start();
include("conn.php");
$post_firstName = $_POST['firstName'];
$post_lastName = $_POST['lastName'];
$post_dateofBirth = $_POST['dateofBirth'];
$post_gender = $_POST['gender'];
$post_propertyNo = $_POST['propertyNo'];
$post_propertyAddress = $_POST['propertyAddress'];
$post_streetAddress = $_POST['streetAddress'];
$post_locality = $_POST['locality'];
$post_email = $_POST['email'];
$post_password = $_POST['password'];
$checkexistsQuery = $conn->prepare('SELECT count(*) AS countExists FROM tbl_account acc WHERE acc.email = ?');
$checkexistsQuery->bind_param('s', $post_email);
$checkexistsQuery->execute();
$checkexistsQuery->store_result();
$checkexistsQuery->bind_result($countExists);
$checkexistsQuery->fetch();
if($countExists > 0){
echo 'error-email-exists';
}else{
$signupQuery = $conn->prepare('insert into tbl_account (name, surname, email, password, dob, genderID, propertyNumber, propertyAddress, streetAddress, localityID) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)');
$signupQuery->bind_param('ssssssssss', $post_firstName,$post_lastName,$post_dateofBirth,$post_gender,$post_propertyNo,$post_propertyAddress,$post_streetAddress,$post_locality,$post_email,$post_password);
if($signupQuery->execute()){
echo 'success';
}else{
echo "Execute failed: (" . $stmt->errno . ") " . $stmt->error;
}
}
?>
问题是没有读取“错误电子邮件存在”和“成功”消息。
【问题讨论】:
-
“不被阅读”是什么意思?具体发生了什么?
-
如果
<?php之前确实有一个新行,那么一些数据会在任何东西之前发送(并且响应将不同于'error-email-exists' -
console.log(response)的结果是什么? -
在
success块旁边写一个error: function(error) { console.log(error)}块以确保输入success。 -
检查是否没有返回空格,因为这会破坏您的
response == "error-email-exists"检查。正是由于这个原因,返回序列化响应格式是更好的做法。快速解决方法是response.trim() === 'error-email-exists',但我建议使用 JSON 来完全避免该问题。
标签: javascript php jquery ajax