I'm using jQuery validation for a registration form in PHP. In my PHP my form is as follow:
<form id="register-form">
<input class="form-control" name="dispName" placeholder="Display name" type="text">
<input class="form-control" name="email" placeholder="Email address" type="email">
<input class="form-control" name="password" id="password" placeholder="Password" type="password">
<input class="form-control" name="password2" placeholder="Re-enter password" type="password">
<input class="btn btn-primary" id="submit-button" type="submit" value="Request Access">
</form>
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.1.3.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.13.0/jquery.validate.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.13.0/additional-methods.min.js"></script>
<script src="request.js"></script>
In my request.js the validation is as follow:
$.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: {dispName: 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."
);
$("#register-form").validate({
rules: {
dispName: {
required:true,
nowhitespace: true,
lettersonly: true,
checkUserName: true
},
email: {
required: true,
email: true,
remote: "http://localhost:3000/inputValidator"
},
pw: {
required: true,
strongPassword: true
},
cpw: {
required: true,
equalTo: '#password'
}
},
messages: {
email: {
required: 'Please enter an email address.',
email: 'Please enter a <em>valid</em> email address.',
}
}
});
in my PHP validation server side:
<?php
$searchVal = $_POST['dispName'];
try {
$dbh = new PDO("mysql:host=$hostname;dbname=$dbname", $username, $password);
$sql = "SELECT * FROM users WHERE dname = " . "'" . $searchVal . "'";
$stmt = $dbh->query($sql);
$result = $stmt->fetch(PDO::FETCH_ASSOC);
if($result){
echo 'true';
}else {
echo 'false';
}
$dbh = null;
}
catch(PDOException $e)
{
echo $e->getMessage();
}
?>
I keep getting This username is already taken! Try another.
even i use name not in the database. I tested on check-username.php
on the server using a dummy "POST" value and it worked fine. So i've got a strong feeling its with the syntax in request.js
. Can anyone point me in the right direction.... Thank in advance...