I'm trying to check on email field blur, if the email already exists in db. My code is now:
<script type="text/javascript">
$(document).ready(function () {
// Validation
$("#soutez").validate({
rules: {
email: {
required: true,
email: true,
remote: "check-email.php",
},
},
messages:{
email:'Email address exists.'
},
onkeyup: false,
onblur: true,
});
});
</script>
And the php code is
$email= $_GET['email'];
echo $email;
$path = $_SERVER['DOCUMENT_ROOT'];
include_once $path . '/wp-config.php';
include_once $path . '/wp-load.php';
include_once $path . '/wp-includes/wp-db.php';
include_once $path . '/wp-includes/pluggable.php';
global $wpdb;
$email_exists = $wpdb->get_row('SELECT COUNT(*) as count from reg_form_new WHERE email = "'.$email.'"');
if ( $email_exists->count == 0 ) { echo 'true'; } else { echo 'false'; }
exit; }
The php code returns true/false correctly, but for some reason it doesn't work with the jQuery script. Anyone can tell me what I'm doing wrong? Thanks
You have to echo exactly the string 'true'
and nothing else if you want it to be allowed through. Anything else ('false'
,null
,undefined
, or any string) will be interpreted as invalid and if there is a string, that string will be displayed.
So check carefully that your php script is printing out only 'true'
or 'false'
for now. The script as you've shown it prints the email followed by 'true'
or 'false'
. This will always be interpreted as false
.
Read the documentation of the remote method:
The response is evaluated as JSON and must be true for valid elements, and can be any false, undefined or null for invalid elements, using the default message; or a string, eg. "That name is already taken, try peter123 instead" to display as the error message.
Use Firebug or Chrome Inspector to verify that your response is correct.
I'm not an expert in Jquery, you can to adapt the working function to your need:
$.ajax({
url: "check-email.php",
type:'GET',
/*you my specify dataType: 'json', for example ...*/
data: $("#soutez").serialize(), //email input id
success: function(res) {
switch(res) {
case ('true'):
alert("true");
break;
case ('false'):
alert('false');
break;
// other cases...
}
}
});