Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery if/else statement with .get not working [closed]

On a new-user registration form, I have a real simple function just to check to see if a username exists in the database. Unfortunately, the else part of the statement isn't working. The PHP file works fine and returns either true or false, as expected. Here's the jQuery:

$('#username').keyup(function() {
        var inp = $('#username').val();
        $.get('register-check-username.php', { username: inp }, function(data) {
            if(data!="false") {
                $('#namecheck').html('✓');
            } else {
                $('#namecheck').html('This username is already taken');
            }
         });
    }); 

If it's not clear, username is the id of the text input. When it's changed the php is checking username availability. Then a <span> tag with id "namecheck" is to change to tell the user what's up. Now, I can change if(data) to if(!data) and it will behave as expected for that change. As it is above, I can get $('#namecheck').html('✓') to happen when it's supposed to, but never the second part of $('#namecheck').html('This username is already taken').

Why is my else line never being called? I've wasted too much time trying to figure this out on my own so now I'm asking you all for some help in figuring out what's going wrong.

edit: With console.log(data) in there, the console returns false when it's false, but nothing is logged when it's true.

Updated if(data) to if(data!="false"). The problem remains.

UPDATE The problem isn't quite what I thought it was. It looks like the script is firing as it should, except it only does .keyup if the input value is 4 characters or less, and the username I've been testing it with is 6 letters. The data returned for the first 4 characters stays put.

So now it looks like the problem is actually that it won't run .get() unless the value is 4 characters or less. I'm looking into what might be causing this in the php.

like image 831
Yhilan Avatar asked May 13 '26 23:05

Yhilan


1 Answers

(data) will always be a truthy value since it is a string

Change to

if (data=="true") ...

If true returns empty (not a clever idea) try

if (data!="false") ...

Live Demo

like image 131
mplungjan Avatar answered May 15 '26 11:05

mplungjan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!