How to Integrate Google reCAPTCHA v3 in Forms that Use AJAX Validation

I recently had to update one of the sites that is using Google reCAPTCHA to use the latest version, Google reCAPTCHA v3, and checked for the documentation and examples provided at Google. Everything is clear and super easy to use/mimic in your code.

However, for this particular functionality that I was updating, the form that is protected with Google reCAPTCHA is using an AJAX validation. I could not find yet a sample of code that is describing how to handle this, as the server side validation was failing. In this case, the form was taking a few minutes to be filled in by the users, and the reCAPTCHA response was timing out because of that, hence, the server side validation was only showing the timeout response.

The solution was to call again the reCAPTCHA render method when processing the AJAX call response and let the users know that there was an issue and that they have to click the submit button again.

Here is the sample from the client side code:

function docaptcha(token) {
	// Do some custom computation here with the token from the Google reCAPTCHA response.
	// Perhaps pass the value in a hidden input for your custom form, etc.
	...
}
function validation() {
	$.ajax({
		url: 'my_server_side_validation_script',
		type: 'post',
		...
		dataType: 'json',
		cache: false
	}).done(function(response, textStatus, jqXHR) {
		// Process the server side validation response and decide if you need to continue.
		...
		
		// Attempt to refresh the reCAPTCHA token.
		grecaptcha.ready(function() {
			grecaptcha.execute(captcha_key, {action: 'instance'}).then(function(token) {
				docaptcha(token);
			});
		});
	});
}

// This is from the Google reCAPTCHA documentation.
grecaptcha.ready(function() {
	grecaptcha.execute(captcha_key, {action: 'instance'}).then(function(token) {
		// This is where I add my custom computation based on the token.
		docaptcha(token);
	});
});

I hope this helps anyone that encounters the same type of validation issue with Google reCAPTCHA v3 when using AJAX calls.


Support my work! Click the button below


See other tips & tricks