通过Jquery检查用户名可用性

时间:2013-12-03 02:55:27

标签: javascript php jquery html ajax

我有一个代码来访问我的数据库并检查是否使用了用户名。然而,无论我总是得到结果"Minimum amount of chars is 3 ",即使你输入长度超过3个字符的用户名,无论它是否存在于数据库中。我做错了什么

这是html:

<p><input type="text" class="span2" maxlength = "20" name="username" required id="username" placeholder="Username" pattern = "[A-Za-z][0-9]" title = "Ex: John123">
<input type='button' class="btn btn-success btn-mini" id='check_username_availability' value='Check Availability'></p>
<div id='username_availability_result'></div> 

这是php文件:

<?php
mysql_connect('localhost', 'root', '*****');  
mysql_select_db('testing');  

//get the username  
$username = mysql_real_escape_string($_POST['username']);  

//mysql query to select field username if it's equal to the username that we check '  
$result = mysql_query('select username from users where username = "'. $username .'"');  

//if number of rows fields is bigger them 0 that means it's NOT available '  
if(mysql_num_rows($result)>0){  
    //and we send 0 to the ajax request  
    echo 0;  
}else{  
    //else if it's not bigger then 0, then it's available '  
    //and we send 1 to the ajax request  
    echo 1;  
}  

?>

最后这里是JQuery:

    <script>
    $(document).ready(function() {  

        //the min chars for username  
        var min_chars = 3;  

        //result texts  
        var characters_error = 'Minimum amount of chars is 3';  
        var checking_html = 'Checking...';  

        //when button is clicked  
        $('#check_username_availability').click(function(){  
            //run the character number check  
            if($('#username').val().length < min_chars){  
                //if it's bellow the minimum show characters_error text '  
                $('#username_availability_result').html(characters_error);  
            }else{  
                //else show the cheking_text and run the function to check  
                $('#username_availability_result').html(checking_html);  
                check_availability();  
            }  
        });  

  });  

//function to check username availability  
function check_availability(){  

        //get the username  
        var username = $('#username').val();  

        //use ajax to run the check  
        $.post("unamecheck.php", { username: username },  
            function(result){  
                //if the result is 1  
                if(result == 1){  
                    //show that the username is available  
                    $('#username_availability_result').html(username + ' is Available');  
                }else{  
                    //show that the username is NOT available  
                    $('#username_availability_result').html(username + ' is not Available');  
                }  
        });  

}  



    </script>

1 个答案:

答案 0 :(得分:0)

您可以按照以下步骤操作,并解决您的问题:

  1. alert($('#username')。val()。length);它不应该是未定义的
  2. 如果您在文本框中输入超过3个字符,那么它将显示结果,即您编写代码的方式。
  3. 在查询数据库时使用预准备语句。
  4. 希望它有所帮助......!