Member Avatar for Member #578978

Hi,

I'm new to JQuery and attempting to write a script to check username availability. My problem is that no matter what I type, I always get back "This username is already in use."

JQuery source:

$(document).ready(function() {

jQuery.validator.addMethod("usernameCheck", function(username) {
   var isSuccess = false;
   $.ajax({ url: "username_availability.php",
            data: "username=" + username,
            async: false,
            success:
                function(msg) { isSuccess = msg === "TRUE" ? true : false }
          });
    return isSuccess;
},"");

    $("#register_form").validate({
        onkeyup:false,
        rules: {
            username: {
                required: true,
                minlength: 3,
                usernameCheck: true    // remote check for duplicate username
            }
        },
        messages: {
            username: {
                required: "username is required.",
                minlength: jQuery.format("username must be at least {0} characters in length."),
                usernameCheck: "This username is already in use."
            }
        }
    });

PHP Source:

include('database_connection.php');                                  
if (isset($_POST['username'])) {                                                               
    $username = mysql_real_escape_string($_POST['username']);                                  
    $check_for_username = mysql_query("SELECT user_id FROM users WHERE username='$username'"); 
    if (mysql_num_rows($check_for_username)) {
        echo "TRUE";                                                                           
    } else {
        echo "FALSE";                                                                           //No Record Found - Username is available
    }
}
?>

HTML Source:

<input class="username" id="username" type="text" name="username" value="" maxlength="20" />&nbsp;

Thanks a lot

Dani AI

Generated

@feoperro a common gotcha with the jQuery Validate remote rule is the server-side return value. The plugin treats true as “this field is valid” (so for a username, true means available) and anything else (false or a string) as invalid. Make sure your endpoint returns true only when no row is found; otherwise you will always see the “taken” message. Remote rule overview. (sitepoint.com)

Skip custom addMethod + async:false. Synchronous XHR blocks the UI and is deprecated in modern browsers. Let the built-in remote rule handle the async check instead. (developer.mozilla.org)

Minimal PHP endpoint (uses PDO, returns JSON boolean expected by remote):

<?php
// username_availability.php
header('Content-Type: application/json');

require 'db.php'; // creates $pdo (PDO connection)

$user = isset($_GET['username']) ? trim($_GET['username']) : '';
$stmt = $pdo->prepare('SELECT 1 FROM users WHERE username = ? LIMIT 1');
$stmt->execute([$user]);

echo json_encode($stmt->fetchColumn() ? false : true);

To show two messages (positive/negative) and a loader with remote, wire these options inside your validate() call:

success: function(label, el) {  // positive feedback when valid
  label.text('Available').addClass('valid');
},
messages: {
  username: { remote: 'That username is taken.' }
},
rules: {
  username: {
    remote: {
      url: '/username_availability.php',
      type: 'get',
      beforeSend: function(){ $('#loading').show(); },
      complete: function(){ $('#loading').hide(); }
    }
  }
}

One more tip for future readers: if your PHP still uses mysql_* calls, migrate to mysqli or PDO. The old ext/mysql API was deprecated in PHP 5.5 and removed in PHP 7, so code relying on it will eventually break. (php.net)

Recommended Answers

All 12 Replies

try:

...
success:
                function(msg) { isSuccess = !/TRUE/.test(msg); }
...
Member Avatar for Member #578978

Same issue...

Do you know where I can find a working example using this type of JQuery validation for username?

did you try the remote option? On the server, you should check for $_GET and return true OR false (lowercase) without any leading and/or trailing spaces.

$(document).ready(function() {

    $("#register_form").validate({
        onkeyup:false,
        rules: {
            username: {
                required: true,
                minlength: 3,
				remote:"username_availability.php"// remote check for duplicate username
            }
        },
        messages: {
            username: {
                required: "username is required.",
                minlength: jQuery.format("username must be at least {0} characters in length."),
                remote: jQuery.format("{0} is already in use")
            }
        }
    });
});
<?php
include('database_connection.php');                                  
if (isset($_POST['username'])) {                                                               
    $username = mysql_real_escape_string($_POST['username']);                                  
    $check_for_username = mysql_query("SELECT user_id FROM users WHERE username='$username'"); 
    if (mysql_num_rows($check_for_username)) {
        echo "true";                                                                           
    } else {
        echo "false";//No Record Found - Username is available
    }
}
exit;
?>
Member Avatar for Member #578978

Now it doesn't show any messages at all...

register.php

<html>
    <head>
        <title>

        </title>

        <script type="text/javascript" src="jquery.min.js"></script>
        <script type="text/javascript" src="jquery-ui.min.js"></script>
        <script type="text/javascript" src="jquery.validate.js"></script>
        <script type="text/javascript" src="custom_validation.js"></script>

    </head>
    <body>

        <form method="post" action="result.php" id="register_form" name="register_form">
            <fieldset>
                <legend>Register</legend>

                <label for="username">Username*</label>
                <input class="username" id="username" type="text" name="username" value="" maxlength="20" />&nbsp;
                <img id="loading" name="loading" src="loading.gif" alt="Loading..." style="display: none;"><br/><br/>

                <input type="submit" value="Submit"/>
            </fieldset>
        </form>

        <br/>

    </body>
</html>

username_availability.php

<?php
include('database_connection.php');
if (isset($_GET['username'])) {
    $username = mysql_real_escape_string($_GET['username']);
    $check_for_username = mysql_query("SELECT user_id FROM users WHERE username='$username'");
    if (mysql_num_rows($check_for_username)) {
        echo "true";
    } else {
        echo "false";//No Record Found - Username is available
    }
}
exit;
?>

custom_

$(document).ready(function() {

    $("#register_form").validate({
        onkeyup:false,
        rules: {
            username: {
                required:true,
                minlength:3,
                remote:"username_availability.php"    // remote check for duplicate username
            }
        },
        messages: {
            username: {
                required: "username is required.",
                minlength: jQuery.format("username must be at least {0} characters in length."),
                remote: jQuery.format("{0} is already in use")
            }
        }
    });
});

Open Firefox, install the Firebug plugin and then restart Firefox. Go to your page. On the lower-right corner of the browser you will see a "bug". Click it and you will see a sub-pane at the bottom of the Firefox. On that pane click on the "Net" menu, then on the "XHR" option/button. Fill your form and submit it. Once you do so, you will see the url that is submitting to and it will be prefixed with POST or GET, depending on the request type. You need to verify that it is in fact doing a GET request (may not be the case depending on your global jquery setting). Then click on the "+" icon to expand it. There should be a "params" tab that shows you what it is sending to the server and on another tab named "response" that shows what it is receiving FROM the server.

If you have a link to your page, it will help (I don't have all those js libraries you are using).

Member Avatar for Member #578978

I tried it and got False for both, for the online one

Member Avatar for Member #578978

the only user that's taken is "test"

OK, I see you have a very outdated version of the validation plugin. Try updating it to the latest first and try again.

Member Avatar for Member #578978

wow it's actually working :O

so... 2 small questions before I post the fixed version:

1. How do I put 2 messages, one for true and one for false? (Currently it only says when a username is not available).

2. How would I set ajax attributes like async, etc while using remote?

Thanks a lot though, it's been a while that I've been stuck with this...

Member Avatar for Member #578978

Oh ya, and where would I put the loader?


Before I had it in my addMethod like:

$('#loading').hide()
    .ajaxStart(function() {
        $(this).show();
    })
    .ajaxStop(function() {
        $(this).hide();
    });
Member Avatar for Member #578978

Thanks a lot, you really went out of your way to help out!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.