我遇到了代码不断显示用户名可用的问题,即使它存在于数据库中。任何人都可以解决我遇到的问题吗?下面是我的代码。
PHP
CoUninitialize
的jQuery
// Define $username
$username=$_POST["emailAddress"];
// Create Connection
$db = new mysqli($server, $user, $password, $database);
// Check Connection
if ($db->connect_error) {
die("Connection failed: " . $db->connect_error);
}
// SQL query to fetch registerd users and finds user match.
$query = "SELECT email_address FROM users WHERE email_address='$username'";
$result = mysqli_query($db,$query);
$rows = mysqli_num_rows($result);
//if number of rows fields is bigger them 0 that means it's NOT available '
if($rows>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;
}
mysqli_close($db); // Closing Connection
}
HTML
$(document).ready(function () {
//when button is clicked
$('[name="checkAvail"]').on("click", function () {
check_availability();
});
});
//function to check username availability
function check_availability() {
//get the username
var username = $('[name="emailAddress"]').val();
//use ajax to run the check
$.post("checkusers.php",
function (result) {
//if the result is 1
if (result == 1) {
//show that the username is available
$('.existingUser').html(username + ' is Available');
} else {
//show that the username is NOT available
$('.existingUser').html(username + ' is NOT Available');
}
});
答案 0 :(得分:1)
你的ajax没有发送任何数据......所以你的php中$_POST["emailAddress"];
将是空的
您需要添加数据对象作为$.post
$.post("checkusers.php",{emailAddress : username },function (result) {
// success handing code left out for clarity
});
此外,您应该检查输入是否为空,然后才允许用户进行检查。向服务器发送无效的空值没有意义。
您可以使用许多简单的JavaScript验证插件。
同样在服务器上应该验证用户输入。这是最重要的验证点,因为javascript可以解决以允许发送任何内容
答案 1 :(得分:0)
您没有向帖子页面发送任何数据。
$.post( "checkusers.php", { emailAddress: username})
.done(function( data ) {
if (data == "1") {
//show that the username is available
$('.existingUser').html(username + ' is Available');
} else {
//show that the username is NOT available
$('.existingUser').html(username + ' is NOT Available');
}
});
答案 2 :(得分:0)
根据你的php脚本尝试这个if(result == 0)
function (result) {
//if the result is 0
if (result == 0) {
//show that the username is available
$('.existingUser').html(username + ' is Available');
} else {
//show that the username is NOT available
$('.existingUser').html(username + ' is NOT Available');
}