I am pulling my hair out trying to figure this out. I have followed the wordpress codex here for AJAX: http://codex.wordpress.org/AJAX_in_Plugins
All I keep returning is 0, I never get a 1. Any idea why? My code is as follows.
PHP:
add_action('wp_enqueue_scripts', 'live_validation' );
add_action('wp_ajax_validate_email', 'validate_email_input');
add_action('wp_ajax_nopriv_validate_email', 'validate_email_input');
function live_validation() {
wp_enqueue_script( "validate_email", STRIPE_BASE_URL . 'inc/js/check-email.js', array( 'jquery' ) );
wp_localize_script( "validate_email", "validateEmail", array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) );
}
function validate_email_input() {
$email = $_POST['email'];
if ( email_exists($email) ) {
echo 1;
} else {
echo 0;
}
exit;
}
JS:
jQuery(document).ready(function($) {
$('input[name=email]').keyup(function() {
var input_value = $(this).val();
$.post( validateEmail.ajaxurl, { action:'validate_email', email:input_value }, function(data) {
$('.message').html(data);
});
});
});
HTML:
<div class="form-row">
<label for="email"><?php _e('Email', 'oe'); ?></label>
<input type="text" size="20" id="email" name="email" />
<span class="message"></span>
</div>
I’ll guess that you’re testing this by entering your admin email address. Have a look at the Codex page for
email_exists()
:If you’re entering the email address of the first user created for a site, the user ID will be
0
, soif ( email_exists($email) )
for that user will evaluate false. The example given on that page does not account for this situation.Found the problem. It always helps to read the codex thoroughly!
http://codex.wordpress.org/Plugin_API/Action_Reference/wp_ajax_%28action%29
Just make sure all of your AJAX requests go in your main plugin file.