1

using

  • jquery validator plugin
  • jquery

try to:

  • make sure a username doesn't exist in the database
    • have a form + a field + remote check
    • i want to let jquery check using ajax if it exists.

what works:

  • check-username.php does work by itself

what doesn't

  • form doesn't seem to be able to pass return boolean value to validate the remote jquery validation
  • how do I get it to pass the value so that the field can be validated?

HTML

    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js" type="text/javascript"></script>
    <script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.min.js" type="text/javascript"></script> 
    <script language="javascript" src="validate.js"></script>

    <meta name="generator" content="" />
    <style type="text/css"></style>
  </head>
<body>

<form action="/" method="post" id="register-form">
    <div>
        <label for="username">Username<font color="red">*</font>:</label> 
        <input type="text" name="username" size="20" id="username" />
    </div>
    <div>
        <input type="submit" name="submit" value="submit" />
    </div>
</form>
</body>
</html>

JQUERY Validate

$().ready(function() {
    // validate signup form on keyup and submit
    $("#register-form").validate({
        rules: {
            username: {
                required: true,
                remote: "check-username.php"
                },
        },
        messages: {
            username:{
                remote: "This username is already taken! Try another."
            },
        },
    });
});

Check-USERNAME.php

<?php

$searchVal = $_POST['username'];

try {
    $dbh = new PDO("mysql:host=$hostname;dbname=$data", $username, $password);

    $sql = "SELECT * FROM users WHERE USERNAME = " . "'" . $searchVal .  "'";
    $stmt = $dbh->query($sql);
    $result = $stmt->fetch(PDO::FETCH_ASSOC);

   if($result>0){
     return true;
   }else {
     return false;
   }

    $dbh = null;
    }
        catch(PDOException $e)
    {
        echo $e->getMessage();
    }       
?>
6
  • move $dbh = null; some rows up. Commented Jun 28, 2013 at 7:18
  • tried but the field doesn't check the db when duplicate value is entered. Commented Jun 28, 2013 at 15:29
  • That is not connected with your issue, but better to disconnect before return. Btw, I'm using this - very simple code for checking used names, etc. Commented Jun 28, 2013 at 17:02
  • i did look at that but don't see a clear example and was wondering was there a simpler way of doing it since the post was in 2009. Commented Jun 28, 2013 at 22:10
  • Do not mind the year, it is working pretty well. See my answer down. Commented Jun 29, 2013 at 5:47

3 Answers 3

8

In order to validate value to server side, you should add new Validation Method.

$().ready(function() {

    $.validator.addMethod("checkUserName", 
        function(value, element) {
            var result = false;
            $.ajax({
                type:"POST",
                async: false,
                url: "check-username.php", // script to validate in server side
                data: {username: value},
                success: function(data) {
                    result = (data == true) ? true : false;
                }
            });
            // return true if username is exist in database
            return result; 
        }, 
        "This username is already taken! Try another."
    );

    // validate signup form on keyup and submit
    $("#register-form").validate({
        rules: {
            "username": {
                required: true,
                checkUserName: true
            }
        }
    });
});        

As stated above, method checkUserName will verify to server side and give error message "This username is already taken! Try another." if username is not exist.

For more info and examples about jQuery Validation and its method : click here.

Hopefully this help.

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

Comments

1

Didn't check the rest of your code, but try this:

<?php
    $searchVal = $_POST['username'];
    try {
        $dbh = new PDO("mysql:host=$hostname;dbname=$data", $username, $password);
        $sql = "SELECT * FROM users WHERE USERNAME = " . "'" . $searchVal .  "'";
        $stmt = $dbh->query($sql);
        $result = $stmt->fetch(PDO::FETCH_ASSOC);

        if($result>0) {
            $valid = "true";
        } else {
            $valid = "false";
        }

        $dbh = null;

        echo $value;
    }
    catch(PDOException $e) {
        echo $e->getMessage();
    }       

?>

1 Comment

the php code already worked itself but for some reason I can't get jquery validator to see the validation value to validate the field.
0

This is a solution using a different plugin from here. For checking name availability using Ajax calls make following:

After downloading attach jquery.validationEngine.js and your locale like:

<script src="js/jquery.validationEngine-en.js" type="text/javascript" charset="utf-"></script>
<script src="js/jquery.validationEngine.js" type="text/javascript" charset="utf-8"></script>

Note, that en locale is also compulsory to be included.

Open and modify your language file, you have to point where is your php file which will check the database for name availability or to use default file name. So, find the following rows in jquery.validationEngine-en.js in case you use English.

 "ajaxUserCallPhp": {
    "url": "phpajax/ajaxValidateFieldUser.php",

Here you can change file name if you want like:

 "ajaxUserCallPhp": {
    "url": "my-file_which_will_check_db.php",

And your my-file_which_will_check_db.php should look like:

<?
/* RECEIVE VALUE */
$validateValue=$_REQUEST['fieldValue'];
$validateId=$_REQUEST['fieldId'];

$validateError= "This username is already taken";
$validateSuccess= "This username is available";

/* RETURN VALUE */
$arrayToJs = array();
$arrayToJs[0] = $validateId;

$dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass); //Connect with your credentials
$stmt = $dbh->query("SELECT * From `users` WHERE `USERNAME` = '{$validateValue}'"); 
$dbh = null;                    // Disconnect

sleep(1); /*added because check is very fast and the label 'checking...' is not visible*/

if ($result = $stmt->fetch()) { 
$arrayToJs[1] = false;          // found user with that name
echo json_encode($arrayToJs);           
}
else {
$arrayToJs[1] = true;
echo json_encode($arrayToJs);       // that user name is free
}
?>

Finally, your HTML markup should look like:

<input type="text" name="user_name" id="user_name" class="validate[required],custom[onlyLetterNumber],maxSize[20],ajax[ajaxUserCallPhp] text-input" />

Note additional class attribute here.

And include following script:

<script>
  $(document).ready(function(){
  $("#register_form").validationEngine();
  });
</script>

Comments

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.