I'm trying to check the existence of an username already registered on my application using jQuery+Ajax+POST.
我正在尝试使用jQuery+Ajax+POST检查应用程序上已经注册的用户名是否存在。
HTML
HTML
<div class="form-group">
<label for="username" class="col-md-3 control-label">Username</label>
<div class="col-md-9">
<input type="text" id="username" class="form-control" name="username" placeholder="Username">
</div>
</div>
<div class="col-sm-9 col-sm-offset-3" id="userCheck">
<div class="alert alert-info" id="userCheckLabel"></div>
</div>
jQuery
jQuery
$('#username').focusout(function() {
var username = $('#username').val();
checkUserExist(username);
})
function checkUserExist($uname) {
$.post( "../core/lib/checkUserExist.php", function( data ) {
if(data.html == 'true') {
$('#userCheck').slideDown("slow");
$('#userCheckLabel').text("This user already exist!")
}
});
PHP
PHP
<?php
require_once('../../core/class.user.php');
$user = new USER();
$uname = $_POST['username'];
$stmt = $user->runQuery("SELECT user_nameFROM users WHERE user_name=:uname ");
$stmt->execute(array(':uname'=>$uname));
$row=$stmt->fetch(PDO::FETCH_ASSOC);
if($row['user_name']==$uname) {
print 'true';
} else {
print 'false';
}
?>
I Don't include class.user.php cause It's only handling the PDO Connection, If I remove the if(data.html == 'true')
the connection work as expected and the message come out.
我不包括class.user。php因为它只处理PDO连接,如果我删除If(数据)。连接按预期工作,消息出来。
Behavior
行为
The code work if I remove the if(data.html == 'true')
. but with this it doesn't do anything, no errors in console. So I think the error is in the way I handle the PHP part. Any suggestion?
如果我删除if(数据),代码就可以工作。html = =“真正的”)。但是它不会做任何事情,在控制台没有错误。我认为错误在于我处理PHP部分的方式。任何建议吗?
1 个解决方案
#1
2
Since you are returning string not HTML, so you have to do like below:-
因为你是返回字符串而不是HTML,所以你必须做如下:-
$.post( "../core/lib/checkUserExist.php",{username: uname }, function( data ) {
console.log(data);// check this and let me know the output
if(data == 'true') { // or try if(data)
$('#userCheck').slideDown("slow");
$('#userCheckLabel').text("This user already exist!")
}
});
#1
2
Since you are returning string not HTML, so you have to do like below:-
因为你是返回字符串而不是HTML,所以你必须做如下:-
$.post( "../core/lib/checkUserExist.php",{username: uname }, function( data ) {
console.log(data);// check this and let me know the output
if(data == 'true') { // or try if(data)
$('#userCheck').slideDown("slow");
$('#userCheckLabel').text("This user already exist!")
}
});