0

After following replies to a previous question on here, I used jQuery to return whether a username was available or not, I found some code on a site, which showed me how to do it. From what I can see, the code seems to be structured correctly, and is connecting to the Database, however even if the name isn't in the Database it returns that it is not Available.

Here is the jQuery(And Registration form) which is included in the register.php file (Will link below jQuery).

<div class="registration">
  <h3>Register - Create a new Account</h3>

  <form action="confirm-registration.php" method="POST">
    <input type="text" name="create-username" id="username" placeholder="Username" maxlength="25" /><input type='button' id='check_username_availability' value='Check Availability'>
<div id='username_availability_result'></div>  <br />
    <input type="password" name="create-password" placeholder="Password" /> <br />
    <input type="password" name="confirm-password" placeholder="Confirm Password" /> <br />
    <input type="email" name="create-email" placeholder="E-mail Address" maxlength="45" /> <br />
    <input type="submit" value="Complete Registration" />
  </form>

  <form>
    <input type="submit" value="Cancel" />
  </form>
</div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<script src="http://maps.googleapis.com/maps/api/js?key=AIzaSyCJnj2nWoM86eU8Bq2G4lSNz3udIkZT4YY&sensor=false"></script>
  <script type="text/javascript" src="/check-user.js"></script>
<script type="text/javascript">
$(document).ready(function() {

        //the min chars for username
        var min_chars = 3;

        //result texts
        var characters_error = 'Minimum amount of chars is 3';
        var checking_html = 'Checking...';

        //when button is clicked
        $('#check_username_availability').click(function(){
            //run the character number check
            if($('#username').val().length < min_chars){
                //if it's bellow the minimum show characters_error text '
                $('#username_availability_result').html(characters_error);
            }else{
                //else show the cheking_text and run the function to check
                $('#username_availability_result').html(checking_html);
                check_availability();
            }
        });

  });

//function to check username availability
function check_availability(){

        //get the username
        var username = $('#username').val();

        //use ajax to run the check
        $.post("check_username.php", { username: username },
            function(result){
                //if the result is 1
                if(result > 0){
                    //show that the username is available
                    $('#username_availability_result').html(username + ' is Available');
                }else{
                    //show that the username is NOT available
                    $('#username_availability_result').html(username + ' is not Available');
                }
        });

}
</script>

The code below links in the final file relevant to this - check-username.php. This is the file that queries the database with the username and then returns it. I will link that below this php.

<?php
    include '../connect.php';

    if (isset($_SESSION['signed_in']) && $_SESSION['signed_in'] == true ) {
      header('Location : http://localhost/blog');
    } else {
      echo include 'registration_form.php';
      require 'check_username.php';
    }
 ?>
<?php
    $username = mysql_real_escape_string(isset($_POST['create-username']));

    //mysql query to select field username if it's equal to the username that we check '
    $result = mysql_query('SELECT user_name from users where user_name = "'. $username .'"');

    //if number of rows fields is bigger them 0 that means it's NOT available '
    if(mysql_num_rows($result) > 0){
      //and we send 0 to the ajax request
      echo 0;
    } else {
      //else if it's not bigger then 0, then it's available '
      //and we send 1 to the ajax request
      echo 1;
    }

Any help with this would be appreciated, this isn't my code and I've not done much jQuery, so after trying a few things I'm now at a complete loss on how to fix it.

Thanks, Ben

1
  • 1
    it's always showing Not Available because the ajax result is not > 0. console.log(result) to see what's being returned. Commented Oct 21, 2015 at 20:56

4 Answers 4

1

This isn't doing what you think:

$username = mysql_real_escape_string(isset($_POST['create-username']));

The result here is going to be something like:

$username = 'true';

Because isset() returns a boolean. You can check if something is set:

if (!isset($_POST['create-username'])) {
    // show an error, stop processing the page
}

But to get the actual value, isset() isn't what you want:

$username = mysql_real_escape_string($_POST['create-username']);

This way you're checking the user input value, and not a boolean value. (It's weird that there's a 'true', or whatever that evaluates to, username in your data. Possibly from another similar error elsewhere, though.)


As a side note, even though you're using mysql_real_escape_string(), you should still investigate upgrading to something like mysqli and using prepared statements with query parameters.

Additional side note: Currently your username comparison is case-sensitive. So 'David' and 'david' would be considered different users. If that's not what you want, you might want to standardize on a casing. Either store the user-input unmodified username and make it upper-/lower-case for comparison, or make it upper-/lower-case before storing and always do the same for other inputs.

Sign up to request clarification or add additional context in comments.

8 Comments

I removed isset() and now I can undefined index, I read that adding isset would solve such an issue on a question on this site. I'm not really sure on how I would get it to work.
@BenJ30: You'd use isset() similar to how I show in an if block in this answer. It's used to check if the value exists before trying to use the value. But it's not used to actually retrieve the value.
I messed up my reply to that comment, what I was meant to say is. I removed the isset as you said and now it returns the error: Notice: Undefined index: username in C:\xampp\htdocs\blog\user\check_username.php on line 2 - I changed it to username due to a reply further down on this answer about the ajax name. However even with it as create-username, I get the same error.
@BenJ30: When you debug this, is the username value present when posting to the server? Examine the POST request being made in your browser's debugging tools which produces that error, see what's included in the request.
Uhmmm, I'm not sure what you mean. How would I go about doing this, sorry about being difficult as well. I'm fairly new to PHP, so really doing some trial-by-error.
|
1

In addition to what has already been mentioned:

In your jQuery, you are using:

$.post("check_username.php", { username: username }...)

which would post "bob" => "bob" as a key/value pair.

Try it like this:

{ "username": username }

Additionally, your PHP is checking for:

$_POST['create-username']

while it should be:

$_POST['username'] 

(should match what you $.post from Ajax)


Use Chromes network console to monitor the request and make sure you are getting the expected results.

Comments

0

You need to normalize your comparison in SQL. See the LOWER() mysql function and strtolower php function. I'd also add a trim() for good measure.

$result = mysql_query('SELECT user_name from users where LOWER(user_name) = "'. strtolower(trim($username)) .'"');

Additionally, you can cut the 5 line if logic at the bottom to one line by just echoing out the echo mysql_num_rows(result);

And yes that isset() should come out.

3 Comments

$username = mysql_real_escape_string(isset($_POST['create-username'])); what is isset doing here : try to remove isset
Yarek is correct, this would pass true or false to the SQL statement instead of the username. (based on nesting)
I removed isset as said above, as well as in David's post and now I get an Undefined index.
-1

$username = mysql_real_escape_string(isset($_POST['create-username']));

$username is taking a wrong value beacause of the isset function: try to remove it.

1 Comment

why is this an answer?

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.