检查电子邮件是否已经存在于数据库jquery + php中 [英] check if email already exists in database jquery +php
问题描述
我正在尝试通过注册表验证电子邮件地址。我想检查数据库中是否存在地址;
Hy I'm trying to validate the email address in a registration form. I want to check if the address exists in the database;
我有以下功能:
function validateEmailRepeat(){
// check if email exists in the database;
var emailVal = $('#email').val();
// assuming this is a input text field
$.post('check_email.php', {'email' : emailVal}, function(data) {
if(data==1)
{
email.addClass("error");
emailInfo.text("Adress exists");
emailInfo.addClass("error");
dataExist=1;
}
else {
email.removeClass("error");
emailInfo.text("Valid adress");
emailInfo.removeClass("error");
dataExist=0;
}
});
if(dataExist==1)
return false;
else
return true;
}
check_email.php如下所示:
the check_email.php looks like this:
require_once('db.php');
if (isset($_POST['email'])){
$email=mysqli_real_escape_string($con,$_POST['email']);
$sql = "SELECT * FROM users WHERE `username`='".$email."'";
$select=mysqli_query($con,$sql) or die("fail");
$row = mysqli_num_rows($select);
if ($row >0) {
echo 1;
}else echo 0 ;
}
else
echo "post error";
我是新的所以不要强硬感谢提前。
i'm new at this . So don't be to tough. thanks in advance.
LE:抱歉!我忘记了这个问题...
问题是我的函数返回true如果我定义var dataExist函数外面的$ .post
,如果我让它喜欢它现在在我得到的函数dataExist未定义错误并返回true
LE:Sorry ! i forgot the question... the problem is that my function returns true if I define var dataExist outside of the function form $.post and if i let it like it is now in the function I get "dataExist is not defined " error and returns true
Le:PHP返回预期的1和0只是我想要的方式..
Le: the PHP returns the expected 1 and 0 just the way i wanted..
LE:
似乎定义了
LE: seems like defining the
var dataExist = 0;
var dataExist=0;
在函数之外 validateEmailRepeat()
解决问题。
如果有另一种方式更优雅,请告诉我这对我来说似乎有些愚蠢。
if there's another way more elegant please tell me because this seems a little stupid to me.
推荐答案
问题是你不能将值返回到被调用的函数中,因为ajax异步工作
The problem is you cannot return the value into the called function, because ajax work asynchronously.
function validateEmailRepeat(){
// check if email exists in the database;
var emailVal = $('#email').val();
// assuming this is a input text field
$.post('check_email.php', {'email' : emailVal}, function(data) {
if(data==1){
email.addClass("error");
emailInfo.text("Adress exists");
emailInfo.addClass("error");
dataExist=1;
}else{
email.removeClass("error");
emailInfo.text("Valid adress");
emailInfo.removeClass("error");
dataExist=0;
}
$('#some_input').val(dataExist);
validateUserName();
});
}
function validateUserName() {
var input = $('#some_input').val();
if (input) {
alert("This username is already taken");// whatever
} else {
// whatever
}
};
这篇关于检查电子邮件是否已经存在于数据库jquery + php中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!