Reputation: 1655
I'm trying to check the existence of an username already registered on my application using jQuery+Ajax+POST.
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
$('#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
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.
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?
Upvotes: 1
Views: 1022
Reputation: 72269
Since you are returning string not HTML, so you have to do like below:-
$.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!")
}
});
Upvotes: 2