Reputation: 105
So I'm trying to create some code that checks if a username is taken. I'm kind of half there and having trouble. I'm new to it and trying to learn how to do it & the code will be messy.
the jquery:
$('#signusername').keyup(function()
{
var username=$('#signusername').val();
if(username != ''){
$.post('username_check.php', {signusername :username}, function(result)
{
if(result==''){
$('.error').text('Avaliable');
} else{
$('.error').text('Taken');
}
}
);
}else{
$('.error').text('???');//this is the the only thing that outputs correctly
}
the php:
function checkUsername($signusername, $conn) {
$stmt = $conn->prepare("SELECT * FROM user_info where username= '".$signusername."'");
$stmt->bindParam(1, $signusername);
$stmt->execute();
if($stmt->rowCount() == 1) {
return TRUE;
}
};
if(isset($_POST['signusername']) && !empty($_POST['signusername'])){
$signusername= $_POST['signusername'];
checkUsername($signusername, $conn);
$result='';
if(checkUsername($signusername, $conn) == TRUE){
$result='';
}else{
$result='';
}
echo $result;
};
I use the same code to check if the username is taken when the form is submitted so I don't think that is the problem. I assume I'm doing something wrong with moving the username variable across? Hope you can help.
Upvotes: 0
Views: 41
Reputation: 524
Try this code
function checkUsername($signusername, $conn) {
$stmt = $conn->prepare("SELECT * FROM user_info where username= '".$signusername."'");
$stmt->bindParam(1, $signusername);
$stmt->execute();
if($stmt->rowCount() == 1) {
return TRUE;
}
return false;
};
if(isset($_POST['signusername']) && !empty($_POST['signusername'])){
$signusername= $_POST['signusername'];
$result = checkUsername($signusername, $conn);
if($result != TRUE){
$result='';
}else{
}
echo $result;
};
Upvotes: 1
Reputation: 13728
Check your console for syntex error };
remove semicolon after }
Also remove function calling two time and you sending result blank in both condition so send some response back to ajax in also fail condition
if(isset($_POST['signusername']) && !empty($_POST['signusername'])){
$signusername= $_POST['signusername'];
$result='';
if(checkUsername($signusername, $conn) == TRUE){
$result='user found';
}else{
$result='user not found';
}
echo $result;
}
Upvotes: 1