为什么我的用户名检查代码不起作用?

时间:2014-03-19 09:54:36

标签: javascript php

我尝试使用javascript / php制作用户名检查代码,现在我无法弄清楚如何做到这一点。

这是我的HTML:

<script type="text/javascript" src="js/jQuery.js"></script>
<script type="text/javascript" src="js/register.js"></script>
...
<input id="username" type="text">

这是我的javascript:

$(function() {
$("#username").change(function() {
// getting the value that user typed
var checkString    = $("#username").val();
if(checkString.indexOf('<') >=0){
document.getElementById('return').innerHTML="Userame contains illigal characters.";
return;
}
if(checkString.indexOf('>') >=0){
document.getElementById('return').innerHTML="Userame contains illigal characters.";
return;
}
if(checkString.indexOf('(') >=0){
document.getElementById('return').innerHTML="Userame contains illigal characters.";
return;
}
if(checkString.indexOf(')') >=0){
document.getElementById('return').innerHTML="Userame contains illigal characters.";
return;
}
if(checkString.indexOf("'") >=0){
document.getElementById('return').innerHTML="Userame contains illigal characters.";
return;
}
if(checkString.indexOf('/') >=0){
document.getElementById('return').innerHTML="Userame contains illigal characters.";
return;
}
if(checkString.indexOf('[') >=0){
document.getElementById('return').innerHTML="Userame contains illigal characters.";
return;
}
    if(checkString.indexOf(']') >=0){
document.getElementById('return').innerHTML="Userame contains illigal characters.";
return;
}
    if($("#Username").val().length < 6){
document.getElementById('return').innerHTML="Your chosen name is too short.";
}
// forming the queryString
var data            = 'user='+ checkString;

// if checkString is not empty
if(checkString) {
    // ajax call
    $.ajax({
        type: "POST",
        url: "validate.php",
        data: data,
        beforeSend: function(html) { // this happen before actual call
        },
        success: function(html){
        if(html == 'free'){
        document.getElementById('return').innerHTML="Username "+ checkString +" is available";
        }
        else if(html == 'taken'){
        document.getElementById('return').innerHTML="Username "+ checkString +" is taken";
        }
        }
    });
}
return false;
});
});

这是我获取数据的php文件(位于/js/validate.php中:

<?php

$user = $_POST['user'];
$user = mysql_real_escape_string($user);
$con = mysqli_connect("localhost","USER","PASS","DB");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

$query = mysqli_query($con,"SELECT `Naam` FROM `main` WHERE `Naam` ='$user';");
$row = mysqli_num_rows($query);
if($row == 0) {
    echo 'free';
} else {
    echo 'taken';
}
?>

1 个答案:

答案 0 :(得分:0)

  1. 检查网址url: "validate.php",,如果您从根文件夹运行代码并且您的php文件位于/js/validate.php中,那么您没有收到任何数据。在crhome检查员看看真正的地址。

  2. 检查数据,你在$ _POST数组中实际收到的内容。

  3. 可能是mysqli_query($con,"SELECT Naam FROM main WHERE Naam ='$user';"); $user解释为$ user字符串而不是变量,那么你需要concat字符串解决方案如='"+$user';"