【发布时间】:2013-12-21 07:12:15
【问题描述】:
我一直在努力尝试使用 ajax 验证电子邮件 使用 PHP 和 Javascript。我想做的是检查电子邮件是否 数据库中已经存在,如果存在,显示一条消息然后去 返回表单,否则显示成功消息并关闭 形式。问题是,如果电子邮件存在,它会显示 “错误消息”,然后显示成功消息。我已经检查过了 类似的问题并尝试了其中的代码,但没有一个适用 正确地满足我的要求。谢谢。
这是我得到的:
// JavaScript Document
$('#btnSubmit').click(function(){
if( validateForm() ){
// code to submit all the info, display the success message and close the form
}
else return false;
});
// I created a function to validate all the fields in the form
function validateForm() {
var firstName = $('#txtFirstName').val();
var lastName = $('#txtLastName').val();
var email = $('#txtMail').val();
// to validate firstName and lastName I do it like this:
if(!firstName || firstName.length === 0) {
message = "All fields are mandatory\\nFirst Name is required";
messageDialog("Warning", message, "warning", 2);
return false;
}
if( !firstName.match(letters) ) {
message = "Invalid name";
messageDialog("Warning", message, "warning", 2);
return false;
}
// So far, no problem at all. But when I tried to validate email:
else {
// use ajax to check if a user has been previously registered
// using this email
$.ajax({
url:"check_user.php", // url that will use
data:{ // data that will be sent
email:email
},
type:"POST", // type of submision
dataType:"text", // what type of data we'll get back
success:function(data)
{
// if check_user returns a number different than 0
// means that there's already a user registered with that email
if(data > 0 ) {
message = "This email is registered already!";
messageDialog("Error", message, "error", 2);
return false;
}
else { return true;}
}
});
}
// if everything is right then return true so the submit function continue its execution
return true;
}
【问题讨论】:
-
ajax 是异步的,你不能从成功回调中返回任何值
标签: javascript php jquery ajax email