To send a Post request from a Form to the server:
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.
0 Comments