我正在尝试使用 ajax 将表单提交到数据库。我已经成功地使用 AJAX 发布到数据库。但不是问题是我不确定如何检查提交的值是否已经存在于数据库中。
我已经有这样做的 php,但我正在尝试使用 AJAX。我正在使用jquery validate 插件以下是代码。
$('#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."
}
},