I\'ve successfully created a form that submits and adds users to a mysql database, and form validation with \'jQuery Validator\' plugin works great for everything except che
js code
username: {
required: true,
minlength: 5,
remote: '/userExists'
},
Php code to check if exist and return messages
public function userExists()
{
$user = User::all()->lists('username');
if (in_array(Input::get('username'), $user)) {
return Response::json(Input::get('username').' is already taken');
} else {
return Response::json(Input::get('username').' Username is available');
}
}
For WordPress & PHP
Most important thing is instead or return true or false, need to echo 'true' or 'false'
jQuery or JS
email: {
required: true,
minlength: 6,
email: true,
remote:{
url : 'your ajax url',
data: {
'action': 'is_user_exist',
},
},
},
WordPress or PHP Backend Code
In backend you will automatically get the value of field via GET method.
/*
*@ Check user exists or not
*/
if( !function_exists('is_user_exists_ajax_function') ):
function is_user_exists_ajax_function() {
$email = $_GET['email'];
if( empty($email) && is_email($email) ):
wp_send_json_error( new \WP_Error( 'Bad Request' ) );
endif;
$is_email = email_exists( $email );
if($is_email):
echo 'false';
else:
echo 'true';
endif;
wp_die();
}
add_action( 'wp_ajax_is_user_exist', 'is_user_exists_ajax_function' );
add_action( 'wp_ajax_nopriv_is_user_exist', 'is_user_exists_ajax_function' );
endif;
$.validator.addMethod("checkExists", function(value, element)
{
var inputElem = $('#register-form :input[name="email"]'),
data = { "emails" : inputElem.val() },
eReport = ''; //error report
$.ajax(
{
type: "POST",
url: validateEmail.php,
dataType: "json",
data: data,
success: function(returnData)
{
if (returnData!== 'true')
{
return '<p>This email address is already registered.</p>';
}
else
{
return true;
}
},
error: function(xhr, textStatus, errorThrown)
{
alert('ajax loading error... ... '+url + query);
return false;
}
});
}, '');
OR
You can use the remote method instead which allows you to do remote checks: http://docs.jquery.com/Plugins/Validation/Methods/remote
Eg.
$("#yourFormId").validate({
rules: {
email: {
required: true,
email: true,
remote: {
url: "checkUnameEmail.php",
type: "post"
}
}
},
messages: {
email: {
required: "Please Enter Email!",
email: "This is not a valid email!",
remote: "Email already in use!"
}
}
});
checkUnameEmail.php //Eg.
<?php
$registeredEmail = array('jenson1@jenson.in', 'jenson2@jenson.in', 'jenson3@jenson.in', 'jenson4@jenson.in', 'jenson5@jenson.in');
$requestedEmail = $_REQUEST['email'];
if( in_array($requestedEmail, $registeredEmail) ){
echo 'false';
}
else{
echo 'true';
}
?>