Help... Ajax callbacks not working with Validation plugin
So I've been trying to setup a registration page to check against certain rules using the Validation plugin. I have to use Ajax to have it check the database for duplicate usernames and email address.
Here is what I have so far...
Validation Code:
-
$().ready(function() {
$("#formRegister").validate({
onkeyup:false,
rules: {
username: {
required:true,
minlength:5,
maxlength:20,
validChars:true,
usernameCheck:true // remote check for duplicate username
}
},
messages: {
username: {
required:"You must provide a username.",
minlength:jQuery.format("Must have at least {0} characters."),
maxlength:jQuery.format("Username must be less than {0} characters."),
validChars:"Please use only valid characters.",
usernameCheck:"Username is unavailable."
}
}
});
});
$.validator.addMethod('validChars', function (value) {
var result = true;
// unwanted characters
var iChars = "!@#$%^&*()+=-[]\\\';,./{}|\":<>?";
for (var i = 0; i < value.length; i++) {
if (iChars.indexOf(value.charAt(i)) != -1) {
return false;
}
}
return result;
}, '');
jQuery.validator.addMethod('usernameCheck', function(username) {
var postURL = "user/json_username_check";
$.ajax({
type: 'post',
dataType: 'json',
data: 'action=usernamecheck&username=' + username,
url: 'test.php',
success: function(m) {
return m;
}
});
}, '');
Obviously, I've cut out all the other fields like email and passwords.
Here's PHP side:
-
if (@$_REQUEST['action'] == 'register') {
// future code to Ajax the entire registration if all validations pass
} else if (@$_REQUEST['action'] == 'usernamecheck') {
// means it was requested via Ajax && isset($_SERVER['HTTP_X_REQUESTED_WITH'])
echo json_encode(usernameCheck($_REQUEST['username']));
exit; // only print out the json version of the response
}
function usernameCheck($username) {
require_once 'database.php';
$query = sprintf("SELECT COUNT(id) FROM users WHERE UPPER(username) = UPPER('%s')",
mysql_real_escape_string($username));
$result = mysql_query($query);
list($count) = mysql_fetch_row($result);
$resp = ($count >= 1) ? false : true;
return $resp;
}
Now, everything validates correctly including the AddMethod I have for detecting invalid characters but the usernameCheck method randomly gives me the error that the username is taken. I even resorted to throwing an 'alert()' into the usernameCheck method to see what Ajax was getting back and it's giving me the right answers...
- type a username that exists and it returns: true
- if username doesn't exist, it returns: false
it seems that the Rule itself doesn't care
Anyone have any ideas?