2

I am new to php and jQuery, I have googled a day but couldn't solve the problem. I want to check if the username is taken or not, but what I got is "Username is Already Taken" no matter what I enter. so here is my code:

$(document).ready(function(){
    $('#registration-form').validate({
    rules: {            
     username: {
            required: true,
            minlength: 3,
            maxlength: 25,
            letters: true,
            checkUsername: true,
        },        
      password: {
            required: true,
            minlength: 6,
            maxlength: 12
        },
    confirmpassword: {
            required: true,
            minlength: 6,
            maxlength: 12,
            equalTo: "#password"
        },        
      email: {
            required: true,
            email: true
        },  

     country:{
            required: true,
     }
            },

        highlight: function(element) {
            $(element).closest('.form-group').addClass('error');
            $(element).removeClass("valid");
        },
        success: function(element) {
            element
            .addClass('valid')
            .closest('.form-group').removeClass('error');
        }
  });

  $(".close, #close").click(function() {
        $("label.error").hide();
        $(".error").removeClass("error");
        $("input.valid").removeClass("valid");
    });

    $.validator.addMethod("letters", function(value, element) {
    return this.optional(element) || value == value.match(/^[a-zA-Z_]+$/);
    },"Letters and underscore only.");

    $.validator.addMethod("checkUsername", function(value, element){
        var response='';
        $.ajax({
            type: "POST",
            url: 'checkname.php',
            data:"username="+value,
            async:false,
            success:function(data){
            response = data;
            }
                });
            if(response == 0)
            {
                return true;
            }
            else
            {
            return false;
            }

    }, "Username is Already Taken");

}); 

Here is my checkname.php

<?php
include 'connect.php';

 if (isSet($_POST['username'])) {                                                               
  $username = mysql_real_escape_string($_POST['username']);                                  
  $check_for_username = mysql_query("SELECT * FROM user WHERE username='$username'"); 
if (mysql_num_rows($check_for_username)>0) {
    echo "false";                                                                           
} else {
    echo "true";                                                                          
}
}


?>

Please help me, I am so frustrated .....

Sparky
  • 98,165
  • 25
  • 199
  • 285
MatthewMT
  • 21
  • 5

1 Answers1

1

You should be using the remote method, which has already been tested and proven for this exact purpose. There is no reason to reinvent something that's already been done.

rules: {            
    username: {
        required: true,
        minlength: 3,
        maxlength: 25,
        letters: true,
        remote: {  // value of 'username' field is sent by default
            type: 'POST',
            url: 'checkname.php'
        }
    }
    ....

Your checkname.php

include 'connect.php';

if (isSet($_POST['username']))
{                                                               
    $username = mysql_real_escape_string($_POST['username']);

    $check_for_username = mysql_query("SELECT * FROM user WHERE username='$username'"); 

    if (mysql_num_rows($check_for_username) > 0)
    {
        echo json_encode("Username is Already Taken");   
        // you could even try something like this:
        // echo json_encode($username . " is Already Taken");                                                                        
    } 
    else 
    {
        echo "true";                                                                          
    }
}

NOTE: mysql_ has been deprecated in PHP and should be replaced with mysqli or pdo_mysql. See: php.net/manual/en/function.mysql-query.php

Also see: jQuery Validate remote method usage to check if username already exists

Community
  • 1
  • 1
Sparky
  • 98,165
  • 25
  • 199
  • 285
  • Thanks for you help. I tried using remote method (and yours suggestion as well), the whole form would have no response, no validate, no message at all, even I click submit without entering anything.... – MatthewMT Jun 10 '15 at 15:40
  • @MatthewMT, it works fine for me and tens of thousands of others. Based on your comment alone, how could I know what you did wrong... a syntax error or the remote file in the wrong location? You have to do some troubleshooting, look at your error console, etc. – Sparky Jun 10 '15 at 15:50
  • It works now :) Silly mistake overlooked the jQuery, found I added one more } to it. Thanks! – MatthewMT Jun 10 '15 at 15:54
  • You saved me a day :) now I will try the email should be more or less the same. – MatthewMT Jun 10 '15 at 15:59