检查数据库中是否存在电子邮件文本框值

时间:2014-12-16 09:17:42

标签: javascript php jquery

我想检查数据库中是否存在文本框中的值,如果数据库中存在该值而不刷新整个页面,则清除该框。

HTML:

<p>Email<input type="text" name="email" id="email" size=18 maxlength=50 required></p>

查询:

$echeck="select email from register where email='$email'";
$echk=mysql_query($echeck);
$ecount=mysql_num_rows($echk);
if($ecount!=0)
{
    echo ("<SCRIPT LANGUAGE='JavaScript'>
    var asign=document.getElementById(email);   //now show null value
    asign.value="";                
    </SCRIPT>");
}

如果我使用提醒,它将刷新页面。

window.alert('Email Id already exist');

2 个答案:

答案 0 :(得分:6)

尝试实现类似的东西:

<script type="text/javascript">
function checkMailStatus(){
    //alert("came");
var email=$("#email").val();// value in field email
$.ajax({
    type:'post',
        url:'checkMail.php',// put your real file name 
        data:{email: email},
        success:function(msg){
        alert(msg); // your message will come here.     
        }
 });
}

</script>

  <p>Email<input type="text" name="email" id="email" onblur="checkMailStatus()"size=18 maxlength=50 required></p>

你的php: checkMail.php

$echeck="select email from register where email=".$_POST['email'];
   $echk=mysql_query($echeck);
   $ecount=mysql_num_rows($echk);
  if($ecount!=0)
   {
      echo "Email already exists";
   }

答案 1 :(得分:1)

我不确定,因为我一直使用JQuery,但我尝试:
资料来源:W3Schools

HTML文件

<script type="text/javascript">
function checkInput(){
            var email=document.getElementById('email').value.trim();
            if(email.length==0)
                 return;
            var xmlhttp=new XMLHttpRequest();
            xmlhttp.onreadystatechange=function(){
              if (xmlhttp.readyState==4 && xmlhttp.status==200){
                    if(xmlhttp.responseText==0){
                        document.getElementById('email').value='';
                        alert('Email already exists');
                    }
                else if(xmlhttp.responseText==1){
                      document.getElementById('email').value='';
                      alert('Invalid Email');      
                }
            }
            xmlhttp.open("GET","check.php?email="+email,true);
            xmlhttp.send();

        }

</script>
//I would use check mail button, to prevent accindental unfocus
<p>Email<input type="text" name="email" id="email" onblur="javascript:checkInput();" size=18 maxlength=50 required></p>

<强> check.php

//This is a simple input check
//The way you check the value isn't secure, you should sanitaze the input
// consider PDO or MySQLi

//Check if email otherwise stop php and clean input
if(!filter_var($_GET['email'], FILTER_VALIDATE_EMAIL)){
    echo '1';
    exit();
}

$echeck="select email from register where email='$_GET['email']'";
$echk=mysql_query($echeck);
$ecount=mysql_num_rows($echk);
if($ecount!=0){
    echo '0';
    exit();
}
else{
    echo '2';
}