How to integrate Google Recaptcha with HTMX - Full Example
If you are having trouble integrating HTMX and Google ReCAPTCHA, please find the below Gist for your reference.
It is actually very surprise to know that HTMX did not have such common integration example.
(Direct link) https://gist.github.com/alucard001/b013a26d72af9b17dadd5e0d575488ef
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<script src="htmx.min.js"></script> | |
<form name="webForm" id="webForm" action="" method="post" role="form" class="form-horizontal clearfix" | |
hx-post="process_result.php" hx-trigger="submit once" hx-target="this" hx-swap="outerHTML transition:true"> | |
<button type="submit" class="btn-register g-recaptcha" aria-label="Submit the form" | |
data-sitekey="<?=SITE_KEY;?>" data-callback="onSubmit" | |
onclick="return onSubmit()">Submit Form</button> | |
</form> | |
<script> | |
function onSubmit(token) { | |
// If reCAPTCHA is already validated (token provided) | |
console.log({token}) | |
if(token) { | |
// Submit form via HTMX | |
htmx.trigger('#webForm', 'submit'); | |
return true; | |
} | |
// Otherwise validate reCAPTCHA | |
if(grecaptcha.getResponse().length === 0) { | |
// Only show alert if validation fails | |
// alert('reCAPTCHA not validated'); | |
// console.log('reCAPTCHA not validated'); | |
return false; | |
} | |
// If reCAPTCHA is valid, proceed with form submission | |
grecaptcha.execute(); | |
// console.log('reCAPTCHA validated'); | |
return false; | |
} | |
// Add HTMX event listener to handle form submission | |
// It works even without async/await. | |
document.getElementById('webForm').addEventListener('htmx:configRequest', async function(evt) { | |
// Add reCAPTcha token to form data | |
evt.detail.parameters['g-recaptcha-response'] = await grecaptcha.getResponse(); | |
// console.log("configRequest") | |
}); | |
</script> |
Comments