我正在尝试使用ajax将表单提交到数据库。我成功地使用AJAX发布到数据库。但问题不在于我不确定如何检查提交的值是否已存在于数据库中。
我已经有了这样做的PHP,但我正在尝试使用AJAX。我正在使用 jquery validate plugin 以下是代码。
$('#subscribeForm').validate({
errorElement: "p",
errorPlacement: function(error, element) {
$('.status').html(error);
},
rules: {
email: {
required: true,
email: true,
remote: {
url: 'index.php',
type: 'post',
data: {
email: function(){
// not sure how to check this
}
}
}
}
},
messages: {
email: {
required: "Please enter your email.",
email: "Please enter a valid email.",
// remote: jQuery.format("{0} is already in use") // doesnt work
}
},
submitHandler: function(form) {
var btn = $(".submit_button");
btn.attr("value", "Submitting..");
$(form).ajaxSubmit({
success: function(){
btn.attr("value", "Submitted");
}
});
return false;
}
});
这是我的PHP:
if(isset($_REQUEST['subscribeForm'])){
$email = trim($_POST['email']);
if(empty($email) || !valid_email($email)){
$status = 'Please provide valid email address.';
} else {
if(email_exist($email)){
$status = 'You are already subscribed.';
} else {
add_email($email);
$status = 'Thank you for subscribing.';
}
}
}
这是我尝试过但又失败了。
if(isset($_REQUEST['subscribeForm'])){
$email = trim($_POST['email']);
if(empty($email) || !valid_email($email)){
$status = 'Please provide valid email address.';
} else {
if(email_exist($email)){
$status = 'You are already subscribed.';
echo false;
} else {
add_email($email);
$status = 'Thank you for subscribing.';
echo true;
}
}
}
我的Javascript
rules: {
email: {
required: true,
email: true,
remote: {
url: 'index.php',
type: 'post'
}
}
},
messages: {
email: {
required: "Please enter your email.",
email: "Please enter a valid email.",
remote: "You are already subscribed."
}
},
答案 0 :(得分:1)
只需回显PHP文件中的错误代码,然后使用Javascript中的AJAX解析错误代码并确定电子邮件是否已注册。
<强> PHP 强>:
define('ERROR_SUCCESS', 0);
define('ERROR_ALREADY', 1);
define('ERROR_INVALID', 2);
if (isset($_REQUEST['subscribeForm'])) {
$email = trim($_POST['email']);
if (empty($email) || !valid_email($email)) {
$status = 'Please provide valid email address.';
echo ERROR_INVALID;
} else {
if (email_exist($email)) {
$status = 'You are already subscribed.';
echo ERROR_ALREADY;
} else {
add_email($email);
$status = 'Thank you for subscribing.';
echo ERROR_SUCCESS;
}
}
}
答案 1 :(得分:1)
你应该在JS中做一些事情,在返回“谢谢订阅”回声时做成功。
尝试;
<强>的Javascript 强>
messages: {
email: {
required: "Please enter your email.",
email: "Please enter a valid email.",
success: "Thank you for subscribing.",
// remote: jQuery.format("{0} is already in use") // doesnt work
}
},
<强> PHP 强>
if(isset($_REQUEST['subscribeForm'])){
$email = trim($_POST['email']);
if(empty($email) || !valid_email($email)){
$status = 'false';
} else {
if(email_exist($email)){
$status = 'false';
} else {
add_email($email);
$status = 'true';
}
}
}
echo $status;