I am running into problems while making a front-end user registration form as part of a custom WordPress theme, and I need to be able to check if an e-mail exists with an ajax request before allowing the user to register.
Here is the JS:
I am using the jQuery Validate plugin, and I am using addMethod to insert into the .validate call. Here is the code:
function chk_email(value){
var response;
$.ajax({
async: false,
url: ajaxurl,
type: 'POST',
data: {action: 'chk_email', email: value},
dataType: "text",
success: function(msg) {
if (msg>0) {
response = true;
} else{
response = false;
}
}
})
console.log(response);
return response;
}
$.validator.addMethod('chk_email', chk_email, "This email address has already been registered");
$("#adduser").validate({
// debug: true,
rules: {
user_login: {
required: true,
minlength: 3,
nowhitespace: true,
alphanumeric: true
},
first_name: {
required: true,
},
last_name: {
required: true,
},
user_email: {
required: true,
email: true,
nowhitespace: true,
// remote: { url: ajaxurl, type: 'post' }
chk_email: true
},
tel: {
required: true,
phoneUS: true
},
street_address: {
required: true
},
locality: {
required: true
},
region: {
required: true
},
postal_code: {
required: true
},
},
messages: {
user_login: {
required: "Required",
user_login: "A username needs to be atleast 3 charachters long."
},
user_email: {
required: "We need your email address to contact you",
user_email: "Your email address must be in the format of name@domain.com",
nowhitespace: "yeah"
},
},
errorElement: 'span',
errorClass: 'help-inline',
errorPlacement: function(error, element) {
error.insertAfter(element);
},
highlight: function(element) {
var parent = $(element).parents('.control-group');
$(element).addClass('error');
$(parent).addClass('error');
},
unhighlight: function(element) {
var parent = $(element).parents('.control-group');
$(element).removeClass('error');
$(parent).removeClass('error');
}
// debug: true
});
And here is the PHP I am using within the functions.php file:
add_action('wp_ajax_nopriv_chk_email', 'chk_email');
function chk_email(){
if (email_exists($_POST['email']) ){
// return TRUE;
echo 'true';
} else {
// return FALSE;
echo 'false';
}
}
I am not quite sure what I am doing wrong here. I would appreciate any thoughts.
http://docs.jquery.com/Plugins/Validation/Methods/remote
Check out the overview and the examples.
So instead of
chk_email()
, you would add to theremote
option: