1

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?

4
  • 1
    you don't sent the username function checkUserExist(uname) { $.post( "../core/lib/checkUserExist.php", {username: uname }, function( data ) { ... Commented Mar 14, 2017 at 19:10
  • I got unexpected token function Commented Mar 14, 2017 at 19:12
  • i have missed comma Commented Mar 14, 2017 at 19:13
  • 1
    @splash58 thanks to you and Alive to Die the code is working now! Commented Mar 14, 2017 at 19:18

1 Answer 1

2

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!")
    }
});
Sign up to request clarification or add additional context in comments.

3 Comments

thanks for the reply, using your suggestion I don't get the alert regarding the user exist
Ok, was a typo in the file path, now it's working as expected, thanks!
@andreaem glad to help you:):)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.