简体   繁体   English

Ajax 检查表单上的注册电子邮件

[英]Ajax check registered email on form

I've taken this script to check if email is registered in DB using ajax.我已经使用这个脚本来检查电子邮件是否使用 ajax 在数据库中注册。 The problem is: It's just checking once, if user insert a registered email and then insert another email the var in checkemail.php do not change.问题是:它只是检查一次,如果用户插入注册的电子邮件,然后插入另一封电子邮件,则 checkemail.php 中的 var 不会改变。

<script type="text/javascript">
    $(document).ready(function() {
        var x_timer;    
        $("#email").keyup(function (e){
            clearTimeout(x_timer);
            var email = $(this).val();
            x_timer = setTimeout(function(){
                check_username_ajax(email);
            }, 600);
        }); 

        function check_username_ajax(email){
            $.post('checkemail.php', {'email':email}, function(data) {
                $("#user-result").html(data);
            });
        }
    });
</script>
<input type="email" name="email" id="email" placeholder="E-mail" /><span id="user-result"></span>

checkemail.php checkemail.php

<?php
    require'conexao.php';
    $email = mysql_real_escape_string($_POST['email']);
    $SQL = "SELECT email FROM clients WHERE email = '" . $email . "'";
    $check = @mysql_query($SQL) or die("Erro no banco de dados!");
    $result = @mysql_num_rows($check);

    if($result){
        $emailstate = "1";
        echo '<script type="text/javascript">alert("O E-mail informado já está cadastrado.");</script>
        <input type="radio" id="emailstate" name="emailstate" value="<?php echo $emailstate; ?>" style="display:none;" checked>';
    } else {
        $emailstate = "0";
        echo '<input type="radio" id="emailstate" name="emailstate" value="<?php echo $emailstate; ?>" style="display:none;" checked>';
    }
?>

Can someone help me please?有人能帮助我吗?

Your question shows code that doesn't make much sense, ie not clear what exactly you are trying to achieve, however this will work to get you on the right track.您的问题显示的代码没有多大意义,即不清楚您究竟想要实现什么,但是这将有助于您走上正确的轨道。

checkemail.php checkemail.php

<?php
if (!empty($_POST['email'])) {
    // Lookup
    $email = $_POST['email'];
    $sql = "SELECT email, username FROM clients WHERE email = '" . mysql_real_escape_string($email) . "' LIMIT 1";
    $result = mysql_query($sql);
    // Format the response package and send back to calling .js function
    $response = new stdClass();
    if (!$result) {
        $response->error = "Could not successfully run query ($sql) from DB: " . mysql_error();
        exit;
    } else {
        $row = mysql_fetch_assoc($result);
        if ($response->exists = mysql_num_rows($result)) {
            // If account exists, get username and add to response data
            $response->username = $row['username'];
        }
    }
    echo json_encode($response);
    exit;
}
?>

client-side html/js:客户端 html/js:

<script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
<script type="text/javascript">
    $(document).ready(function () {
        $("#email").blur(function (e) {
            var email = $(this).val();
            check_username_ajax(email);
        });

        function check_username_ajax(email) {
            $.post('checkemail.php', {'email': email}, function (data) {
                //uncomment the line below to inspect the response in js console/firebug etc
                //console.log(data);
                if (data.hasOwnProperty('error')) {
                    $("#user-result").html(data.error);
                } else {
                    if (data.exists == '1') {
                        $("#user-result").html('Account exists, username is: ' + data.username);
                    } else {
                        $("#user-result").html('Account does not exist');
                    }
                }
            }, "json");
        }
    });
</script>
<div>
    <input type="email" name="email" id="email" placeholder="E-mail" />
    <span id="user-result"></span>
</div>

You could add other properties to the PHP response object like this: $response->username and then access the variable in the js ajax/post response like this: data.username .您可以像这样向 PHP 响应对象添加其他属性: $response->username然后像这样访问 js ajax/post 响应中的变量: data.username

As the other commenters have said, loose the 'setTimeout' with the arbitrary delay, it's not really applicable here, perhaps you will find onBlur more appropriate as shown or perhaps wrap into a full form - as it stands it is not clear what your intended usage is.正如其他评论者所说,通过任意延迟取消“setTimeout”,它在这里并不真正适用,也许您会发现 onBlur 更合适,如图所示,或者可能包装成完整形式 - 就目前而言,目前尚不清楚您的意图用法是。

checkemail.php checkemail.php

<?php
    require'conexao.php';
    $sql = "SELECT email FROM clients WHERE email = '" . mysql_real_escape_string($email) . "' LIMIT 1";
    $echk=mysql_query($sql);
    $ecount=mysql_num_rows($echk);
    if($ecount!=0)
    {
        $emailstate = "1";
        echo '<script type="text/javascript">alert("O E-mail informado já está cadastrado.");</script>
        <input type="radio" id="emailstate" name="emailstate" value="<?php echo $emailstate; ?>" style="display:none;" checked>';
    } else {
        $emailstate = "0";
        echo '<input type="radio" id="emailstate" name="emailstate" value="<?php echo $emailstate; ?>" style="display:none;" checked>';
    }
?>

js js

<script type="text/javascript">
            function checkMailStatus(){
            var email=$("#email").val();
            $.ajax({
                type:'post',
                    url:'checkemail.php',
                    data:{email: email},
                    success:function(msg){
                        $("#user-result").html(msg);
                    }
             });
            }
        </script>

html html

<input type="email" name="email" id="email" placeholder="E-mail" onblur="checkMailStatus()"/><span id="user-result"></span>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM