HTMX Form Submission
Submit forms in your application without writing custom JavaScript using HTMX.
HTMX 2.0 Example
Section titled “HTMX 2.0 Example”By default, HTMX 2.0 restricts requests to the same origin (selfRequestsOnly: true). Since Formkove’s API endpoint is hosted on https://app.formkove.com, you must configure HTMX to allow cross-origin requests, load the json-enc extension, and strip out any default HX- request headers to comply with CORS preflight policies.
HTML Form Code
Section titled “HTML Form Code”<!-- Enable cross-origin requests for HTMX 2.0 --><meta name="htmx-config" content='{"selfRequestsOnly": false}'>
<!-- Load HTMX and the json-enc extension --><script src="https://unpkg.com/htmx.org@2.0.10/dist/htmx.min.js"></script><script src="https://unpkg.com/htmx.org@2.0.10/dist/ext/json-enc.js"></script>
<!-- The form submits JSON and targets a result div --><form id="htmx-form" hx-post="https://app.formkove.com/api/forms/YOUR_FORM_ID/submissions" hx-ext="json-enc" hx-target="#htmx-result" hx-swap="innerHTML"> <div> <label for="htmx-name">Name</label> <input id="htmx-name" name="name" type="text" required> </div> <div> <label for="htmx-email">Email</label> <input id="htmx-email" name="email" type="email" required> </div> <div> <label for="htmx-message">Message</label> <textarea id="htmx-message" name="message" required></textarea> </div>
<button type="submit">Send Message</button>
<div id="htmx-result"></div></form>
<script> // Strip custom HX- headers to satisfy target CORS preflight policies document.body.addEventListener('htmx:configRequest', function(e) { for (const header in e.detail.headers) { if (header.toLowerCase().startsWith('hx-')) { delete e.detail.headers[header]; } } });
// Handle backend responses (success & error message parsing) document.body.addEventListener('htmx:afterOnLoad', function(e) { if (e.detail.elt.id === 'htmx-form') { const result = document.getElementById('htmx-result'); try { const json = JSON.parse(e.detail.xhr.responseText); if (e.detail.xhr.status === 201) { result.innerHTML = '<p class="text-green-600">Message sent successfully!</p>'; e.detail.elt.reset(); } else { result.innerHTML = '<p class="text-red-600">' + (json.error || 'Error') + '</p>'; } } catch { result.innerHTML = '<p class="text-red-600">Invalid response from server.</p>'; } } });</script>Key Points
Section titled “Key Points”- HTMX sends standard key-value payloads by default. The
json-encextension encodes input data intoapplication/jsonformat. - Adding the
htmx:configRequestevent listener is critical for removing theHX-Request,HX-Trigger, and other custom headers to prevent browser preflight CORS request failures.
