Background
I have a registration form that validates with AJAX using jQuery Validation Engine. The form was created using Theme My Login and contains reCaptcha which I implemented using WP-reCAPTCHA.
Just like the rest of the fields, I needed to validate reCaptcha using AJAX as well, that is, without refreshing the whole page. So far I managed to make it work when the Captcha didn't validate. But when it did validate, ie. the input was correct, the page refreshed but with an error message which says 'That reCAPTCHA response was incorrect'. Thus, the form was not saved.
I tried using console.log()
to check the output and the result is 'valid'. So I can't really tell where I went wrong.
Currently I'm testing this locally using XAMPP.
The Code That I Used
The Javascript:
(function($){
// Validate Captcha
$.fn.validateCaptcha = function() {
challengeField = $('input#recaptcha_challenge_field').val();
responseField = $('input#recaptcha_response_field').val();
$.ajax({
type: 'POST',
url: the_ajax_script.ajaxurl,
data: 'action=validate_captcha&recaptcha_challenge_field=' + challengeField + '&recaptcha_response_field=' + responseField,
async: false,
success:function(result)
{
//console.log( result );
if(result != 'Valid') {
$('#captchaError').html('<p class="error">The security code you entered did not match. Please try again.</p>');
$captchaFlag = 'Invalid';
Recaptcha.reload();
} else {
$('#memberInformation span').css({'color':'green'});
$('#memberInformation span').html(html.message).show(3000);
$('#captchaError').html('<p>Success!</p>');
$captchaFlag = 'Valid';
dataString = form.serializeArray();
getSearchMembers(dataString);
}
}
}).responseText;
}
$('#registerform').submit(function() {
var form = $(this);
if (form.validationEngine('validate')) {
$('#memberInformation span').html('');
form.validateCaptcha();
} else {
$('#memberInformation span').css('color','#ff0000').html('Please fill out required fields').show(3000);
}
return false;
});
})(jQuery);
The PHP:
function validate_Captha() {
$privatekey = "xxxxxxxxxx"; //<!----- private key here
$resp = recaptcha_check_answer ($privatekey,
$_SERVER["REMOTE_ADDR"],
$_POST["recaptcha_challenge_field"],
$_POST["recaptcha_response_field"]);
if (!$resp->is_valid) {
// Incorrect CAPTCHA input
echo "Error\n";
die ("The reCAPTCHA wasn't entered correctly. Please go back and try it again.\n(reCAPTCHA said: " . $resp->error . ")");
} else {
echo "Valid";
die();
}
}
add_action( 'wp_ajax_validate_captcha', 'validate_Captha' );
add_action( 'wp_ajax_nopriv_validate_captcha', 'validate_Captha' );