php - 检查用户名是否可用于 AJAX

标签 php javascript ajax

我正在使用带有 AJAX 的基本注册表单,但该表单未连接到数据库。我显然忽略了一些事情。

这是我要验证的字段。

Username:<input type="text" name="user" id="user" maxlength="30">
<span id="msgbox" style="display:none"/></input>

然后我使用 jQuery,代码如下:

$(document).ready(function() {
    $("#user").blur(function() {

        //remove all the class add the messagebox classes and start fading
        $("#msgbox").removeClass().addClass('messagebox').text('Checking...').fadeIn("slow");
        //check the username exists or not from ajax
        $.post("user_availability.php",{ user_name:$(this).val() },
            function(data) {
                if(data=='no') { //if username not avaiable
                    $("#msgbox").fadeTo(200,0.1,function() {//start fading the messagebox
                        //add message and change the class of the box and start fading
                        $(this).html('This User name Already exists').addClass('messageboxerror').fadeTo(900,1);
                    });       

                } else {
                    $("#msgbox").fadeTo(200,0.1,function() { //start fading the messagebox
                        //add message and change the class of the box and start fading
                        $(this).html('Username available to register').addClass('messageboxok').fadeTo(900,1);   
                    });
                } // else
             } // function

        ); // $.post
    }); // blur
}); // ready

我有这个代码,user_availability.php:

mysql_connect(localhost,$user,$password);
    or die('There is error to connect to server:-'.mysqli_connect_error());

$db_selected = mysql_select_db($database);
$user_name=$_POST['user_name'];
$sql = "select * from members where username='$user_name'";
$result = mysql_query($sql);

while($row = mysql_fetch_assoc($result))   
{
    $existing_users[] = $row['username'];
}

if (in_array($user_name, $existing_users))
{
    echo "no"; //user name is not availble
}
else
{
    echo "yes"; //user name is available
}

我没有收到任何数据库错误。表格会更充实,但我无法让它在这个领域工作。有什么建议吗?

最佳答案

只是对 select 语句的挑剔。由于您只需要获取输入的用户名存在多少行,因此不需要执行“select *”,因为根据用户表中的列数,您可能会返回相当多的数据。我会将您的查询修改为如下所示:

$sql = "select COUNT(username) from members where username=$user_name";

然后检查以确保查询结果等于零。如果是,则用户名可用。

我知道上面的内容并不能回答你的问题,但我只是想指出这一点,因为这看起来是一个会被大量调用的函数,具体取决于你的注册表单上的流量和创造力您的访客数量。

关于php - 检查用户名是否可用于 AJAX,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3393148/

相关文章:

jquery 表单未按预期工作。 ajaxForm 不是一个函数

javascript - 使用 jquery 或 javascript 通过 AJAX 读取嵌套的 JSON 并输出到表

php - <button> 点击执行mysql查询

javascript - SyntaxError : expected expression, 在使用 jquery 提交表单时得到 ')'

javascript - AngularJS 在指令中将对象转换为字符串

javascript - 无法使用 "document.getElementById.value"为变量赋值

php - Kohana 3.3 无法从子目录工作

php - 自动安装 WordPress?

javascript - 使用第一个复选框启用广播列表

javascript - 如何为 "Search"函数执行自动提交?