ReCaptcha 2.0 With AJAX
Getting reCAPTCHA v2 to work is straightforward when a form submits naturally via HTTP POST. The browser handles the token generation and transmission in one seamless flow. However, switching to an AJAX submission pattern introduces a specific friction point: the browser never sends the g-recaptcha-response token automatically with your custom data payload. If you simply append g-recaptcha-response to your data string without triggering the reCAPTCHA API first, the server receives an empty value or misses the input entirely, resulting in a missing-input-response error.
The core issue isn't that the token is inaccessible; it's that the JavaScript library responsible for generating it hasn't been explicitly instructed to expose the value before you read it. In standard form submissions, Google's script listens for the form's submit event and automatically triggers the response callback. When you intercept the click event on a custom button and fire an AJAX request immediately after reading the field, that automatic trigger might not have fired yet, or the internal state of the reCAPTCHA widget isn't synced with your manual read operation.
To resolve this, you must explicitly call grecaptcha.execute() before accessing grecaptcha.getResponse(). This forces the reCAPTCHA library to validate the current user interaction and generate a fresh token.
Here is the corrected approach:
$('#submit').click(function(e) {
e.preventDefault(); // Stop the default form submission
var $errors = $('#errors'),
name = $('#name').val(),
email = $('#email').val(),
msg = $('#message').val();
// Basic validation logic here...
if (!name || !email || !msg) {
errors = "All fields are required.";
$errors.text(errors).slideDown();
return;
}
// CRITICAL STEP: Explicitly execute the reCAPTCHA first.
// This ensures a valid token is generated and available in the response object.
grecaptcha.execute('YOUR_SITE_KEY', {action: 'submit'}).then(function(token) {
// Now you can safely read the response
var captchaResponse = token;
if (!captchaResponse) {
$errors.text("reCAPTCHA verification failed.").slideDown();
return;
}
$.ajax({
type: "POST",
url: "sendmail.php",
data: {
email: email,
name: name,
msg: msg,
g-recaptcha-response: captchaResponse
},
success: function(response) {
// Handle server response
if (response === 'ok') {
$('#status').text('Thanks! Your message has been sent.');
$('#status').slideDown();
$('#name, #email, #message').val('');
} else {
$errors.text("reCAPTCHA verification failed on server.").slideDown();
}
},
error: function() {
$errors.text("Network error. Please try again.").slideDown();
}
});
}).catch(function(err) {
// Handle errors from the execute call
console.error('reCAPTCHA error:', err);
});
});
The grecaptcha.execute() method returns a promise that resolves to the token string. By chaining your AJAX request inside this .then() block, you ensure the server receives the valid token immediately after generation. You can also pass an action parameter (e.g., 'submit') to help reCAPTCHA understand the context of the submission, which can be useful for specific fraud detection rules.
On the backend, your PHP logic remains largely unchanged regarding how it fetches the token from $_POST['g-recaptcha-response']. However, you must ensure your site secret is securely stored and not hardcoded in client-side scripts or public repositories. The verification process using file_get_contents to hit the Google API endpoint works identically whether the request comes from a standard form post or an AJAX call, provided the token was generated correctly on the client side.
One common pitfall to avoid is attempting to read grecaptcha.getResponse() before calling execute(). While the library caches responses for valid inputs, relying on the automatic submission handler logic when using custom buttons can lead to race conditions where the token is empty. Explicit invocation guarantees synchronization between the UI interaction and the data payload.
For developers building complex applications with Laravel or other frameworks, this pattern scales well. If you are managing multiple reCAPTCHA instances on a page (e.g., different site keys for distinct forms), ensure you pass the correct sitekey to the execute function corresponding to the form being submitted. This maintains security integrity across your entire application stack.