Skip to content

Instantly share code, notes, and snippets.

@alucard001
Last active March 31, 2025 02:35
Show Gist options
  • Save alucard001/b013a26d72af9b17dadd5e0d575488ef to your computer and use it in GitHub Desktop.
Save alucard001/b013a26d72af9b17dadd5e0d575488ef to your computer and use it in GitHub Desktop.
HTMX + Google Recaptcha
<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>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment