Member Avatar for feoperro

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

try:

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

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 feoperro

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_validation.js

$(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 feoperro

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

Member Avatar for feoperro

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 feoperro

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 feoperro

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 feoperro

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.