在注册表中检查用户名

时间:2015-04-25 12:15:17

标签: javascript php html mysql

在以下代码中,我希望在提交表单之前检查用户名是否可用。我使用onchange()事件和用户名字段。

HTML代码:

<form method="post" action="RegConf.php">
    <p>
        <input type="text" id="username" name="username" value="" placeholder="Username" onchange="check_ava()"> 
        <span id='ava_result'>
    </p>
    <p>
        <input type="password" id="password" name="password" value="" placeholder="Password">
    </p>
    <p>
        <input type="password" id="confPassword" name="confPassword" value="" placeholder="Confirm Password" onchange="check()"> 
        <span id='message'>
    </p>
    <p>
        <input type="text" name="email" value="" placeholder="Email">
    </p>
    <p>
        <input type="text" name="phone" value="" placeholder="Phone">
    </p>
    <p>
        <input type="text" name="address" value="" placeholder="Address">
    </p>
    <p class="submit">
        <input type="submit" id="submit" name="commit" value="Submit">
        <button type="reset" value="Reset">Reset</button>
    </p>
</form>
function check_ava() {  
    var username = document.getElementById('username').value;  
    $.post("check_username.php", { username: username }, function(result){   
        if (result == 1) {  
            document.getElementById('ava_result').innerHTML = "Username is available";
            document.getElementById('submit').disabled = false;
        } else {  
            document.getElementById('ava_result').innerHTML = "Username is not available";
            document.getElementById('submit').disabled = true;
        }  
    });  
} 
<?php
    include 'DBConnection.php';

    $username = mysql_real_escape_string($_POST['username']);  
    $result = mysql_query('select Name from User where Name = "'. $username .'"');  
    if (mysql_num_rows($result) > 0) {  
        echo 0;  
    } else {  
        echo 1;  
    }
?>

问题是它无法正常工作而且没有检查用户名。

1 个答案:

答案 0 :(得分:0)

你必须使用远程方法:

<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.13.1/jquery.validate.min.js"></script>  
<script> 
    $(function() {
                $('#form-validation').validate({

                    rules: {

                        username: {
                            required: true,
                            remote: {
                            url: "check_username.php",
                            type: "post"
                     }
                        },

                    },
                    messages: {
                      val_number: 'Please enter a Value!',

                    }
                });  
            });
</script>

,你的check_username.php是,

$registeredName[] = //select all names in your databse using select and store here as array, 

$requestedName  = $_POST['username'];
if(in_array($requestedName,$registeredName))
{
    echo 'false';
}
else
{
    echo 'true';
}