HTMX - Send a Post request on Form Submit
To send a POST request using the HTMX library in Python, you can use the htmx.post() function. It send a POST request to the server with form data.
Send a Post request on Form Submit in HTMX
To send a Post request from a Form to the server:
- Create a form with some input fields and submit button. You will have to assign the name property to each input so that the server script can get the input values.
- Add hx-post property to the form and assign the URL of the POST request to it.
- if you want to show the response from the server after submitting the request you can use the property hx-target.
Code example:
Here is an example of sending a POST request to a server-side script.
<form hx-post="/submit-form" hx-target="#response">
<label>Name: <input type="text" name="name"></label>
<label>Email: <input type="email" name="email"></label>
<input type="submit" value="Submit">
</form>
<div id="response"></div>
In this example, the form element has an hx-post attribute set to the URL of the server-side script that will handle the form submission. The hx-target attribute is set to the id of the div element that will display the response from the server.
When the form is submitted, the htmx.post() function will send a POST request to the specified URL with the form data as the payload. The response from the server will be inserted into the div element with the id of "response".
Show loader on form submit
<form hx-post="/submit-form" hx-target="#response" hx-indicator="#indicator">
<label>Name: <input type="text" name="name"></label>
<label>Email: <input type="email" name="email"></label>
<input type="submit" value="Submit">
<img id="indicator" class="htmx-indicator" src="/loading.gif"/>
</form>
<div id="response"></div>
To show a loader while the request is processing you can use the hx-indicator attribute and pass the id of the loading image or text that you have created.
In the code example, we have created an indicator using image loading.gif image and it has an id indicator that we have passed in hx-indicator.
Note that the htmx library only works with javascript, so you need to include the library in your HTML file and also run this in a browser and not on a server.