Step 1: Design the Form
First, we need an HTML form. This form will include input fields and a submit button, sending data to the server via htmx.
html<form id="myForm" hx-post="/submit-form" hx-target="#myForm" hx-swap="outerHTML"> <input type="text" name="username" placeholder="Username"> <input type="email" name="email" placeholder="Email"> <button type="submit">Submit</button> </form>
Step 2: Server-Side Handling
On the server side, you need to handle POST requests. While this example does not specify backend languages or frameworks, the key point is that after processing the form data, you can return a special trigger to instruct the client to reset the form.
Assuming your backend is Python Flask, the handling might look like this:
python@app.route('/submit-form', methods=['POST']) def handle_form(): # Process form data # ... # Return HMX instruction: trigger a custom event, such as 'reset-form' return Response("", headers={"HX-Trigger": "reset-form"})
Step 3: Client-Side Event Listening
On the frontend, you need to listen for this custom reset-form event. When triggered, it will reset the form.
html<script> document.body.addEventListener('reset-form', function() { document.getElementById('myForm').reset(); }); </script>
This JavaScript code listens for the reset-form event across the entire body and executes the form reset operation upon receiving it.
Summary
This example demonstrates how to use htmx to interact with the server and handle response events for form reset. By using the HX-Trigger response header, the server can instruct the client to execute specific JavaScript operations, enabling more flexible and powerful client-server interactions.