javascript 如何使用ajax检查数据库中已存在的电子邮件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32924271/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 15:55:43  来源:igfitidea点击:

How to check Email already exist in db using ajax?

javascriptphpjqueryajax

提问by Jinson Varghese

I am after a code for getting ajax response for checking whether an email address is already entered in the database. Here is my code snippet.

我正在寻找获取 ajax 响应的代码,以检查电子邮件地址是否已输入数据库中。这是我的代码片段。

Java Script:

Java脚本:

<script type="text/javascript">
pic1 = new Image(16, 16);
pic1.src="img/loader.gif";

$(document).ready(function(){

$("#email").change(function() {

var usr = $("#email").val();

if(usr.length >= 4)
{
$("#status").html('<img style="width:17px;" src="img/loader.gif" align="absmiddle">&nbsp;Checking availability...');

    $.ajax({ 
    type: "POST", 
    url: "check.php", 
    data: "email="+ usr, 
    success: function(msg){ 

   $("#status").ajaxComplete(function(event, request, settings){

    if(msg == 'OK')

    {
     alert ("error");

        $("#email").removeClass('object_error'); // if necessary
        $("#email").addClass("object_ok");
        $(this).html('&nbsp;<img src="tick.gif" align="absmiddle">');
    } 
    else 
    { 
        $("#email").removeClass('object_ok'); // if necessary
        $("#email").addClass("object_error");
        $(this).html(msg);
    } 

   });

 }

  });

}
else
    {
    $("#status").html('<font color="red">' +
'Enter Valid Email</font>');
    $("#email").removeClass('object_ok'); // if necessary
    $("#email").addClass("object_error");
    }

});

});
</script>

My Check.php file is as follows

我的Check.php文件如下

<?php
// This is a sample code in case you wish to check the username from a mysql db table

if(isSet($_POST['email'])) {
$email = $_POST['email'];

$dbHost = 'localhost'; // usually localhost
$dbUsername = 'root';
$dbPassword = '';
$dbDatabase = 'jaquar_cdb';

$db = mysql_connect($dbHost, $dbUsername, $dbPassword)
 or die ("Unable to connect to Database Server.");
mysql_select_db ($dbDatabase, $db)
 or die ("Could not select database.");

$sql_check = mysql_query("select email from jaquar_contest where email='".$email."'")
 or die(mysql_error());

if(mysql_num_rows($sql_check)) {
    echo '<font color="red">The email <strong>'.$email.'</strong>'.
' is already in use.</font>';
} else {
    echo 'OK';
}
}
?>

Finally the HTML code

最后是 HTML 代码

<div class="sf_columns column_3">                     
 <input id="email" type="text" placeholder="Email" name="email" data-required="true" data-email="true">
 <div style="left:0px;  padding-top: 10px;" id="status"></div>
</div>

The problem is that, I am not getting any response.. What is my mistake? Kindly help me..

问题是,我没有得到任何回应..我的错误是什么?请帮助我..

回答by Shehary

The problem why not getting any response is here with AjaxComplete function

使用AjaxComplete 函数为什么没有得到任何响应的问题就在这里

$("#status").ajaxComplete(function(event, request, settings)

I'm not sure why you are using it but you can do without it and infact even it's not necessary with your approach

我不确定你为什么要使用它,但你可以不用它,事实上,即使你的方法没有必要

without Ajaxcomplete functionmade some changes in code.

没有Ajaxcomplete function对代码进行一些更改。

pic1 = new Image(16, 16);
pic1.src="img/loader.gif";
$(document).ready(function(){
    $("#email").change(function() {
    var usr = $("#email").val();
    if(usr.length >= 4){
        $("#status").html('<img style="width:17px;" src="img/loader.gif" align="absmiddle">&nbsp;Checking availability...');
        $.ajax({ 
        type: "POST", 
        url: "check.php", 
        data: "email="+ usr,
        dataType: 'text',
            success: function(msg){
                if(msg == 'OK'){
                 alert ("success");
                    $("#email").removeClass('object_error'); // if necessary
                    $("#email").addClass("object_ok");
                    $("#status").html('&nbsp;<img src="tick.gif" align="absmiddle">');
                } else {
                    alert ("error");
                   $("#email").removeClass('object_ok'); // if necessary
                   $("#email").addClass("object_error");
                   $("#status").html(msg);
               }
            }

        });
    } else {
        $("#status").html('<font color="red">' + 'Enter Valid Email</font>');
        $("#email").removeClass('object_ok'); // if necessary
        $("#email").addClass("object_error");
    }
    });
});

SideNote: mysql_* functionsis deprecated, so should stop using it and start using MySQLi

旁注:不推荐使用mysql_* 函数,所以应该停止使用它并开始使用 MySQLi

<?php
// This is a sample code in case you wish to check the username from a mysql db table
if(isset($_POST['email'])) { //change isSet to isset (it will not make any difference)
    $email = mysql_real_escape_string($_POST['email']); //escape the string

    $dbHost = 'localhost'; // usually localhost
    $dbUsername = 'root';
    $dbPassword = '';
    $dbDatabase = 'jaquar_cdb';
    $db = mysql_connect($dbHost, $dbUsername, $dbPassword)
        or die ("Unable to connect to Database Server.");
    mysql_select_db ($dbDatabase, $db)
        or die ("Could not select database.");

    $sql_check = mysql_query("SELECT email FROM jaquar_contest WHERE email='$email'") or die(mysql_error());
        if(mysql_num_rows($sql_check) > 0) { //check rows greater then zero (although it will also not make any difference)
            echo '<font color="red">The email <strong>'.$email.'</strong>'. ' is already in use.</font>';
        } else {
            echo 'OK';
        }
}
?>

回答by dexter

Change your first line of php code to :

将您的第一行 php 代码更改为:

if(isset($_POST['email']))

if(isset($_POST['email']))

And so your updated Check.phpfile:

所以你更新的Check.php文件:

<?php
// This is a sample code in case you wish to check the username from a mysql db table

if(isset($_POST['email'])) {
$email = $_POST['email'];

$dbHost = 'localhost'; // usually localhost
$dbUsername = 'root';
$dbPassword = '';
$dbDatabase = 'jaquar_cdb';

$db = mysql_connect($dbHost, $dbUsername, $dbPassword)
 or die ("Unable to connect to Database Server.");
mysql_select_db ($dbDatabase, $db)
 or die ("Could not select database.");

$sql_check = mysql_query("select email from jaquar_contest where email='".$email."'")
 or die(mysql_error());

if(mysql_num_rows($sql_check)) {
    echo '<font color="red">The email <strong>'.$email.'</strong>'.
' is already in use.</font>';
} else {
    echo 'OK';
}
}
?>