I have a form in a boostrap modal that I am posting with HTMX. The post is working great and so is validation. The problem is the successful submit response. I am returning ASP.NET MVC Ok(); method which returns 200.
I want the modal to close after 200.
I tried this code:
<form
hx-post="@Url.Action("Edit", "Vendors", new { Model.Vendor.VendorId })"
hx-target="#edit-vendor-form-container"
hx-encoding='multipart/form-data'
hx-on:htmx:after-on-load="$('#edit-vendor-modal').modal('hide');"
It is not working. Why?
I tried hx-on:htmx:afterOnLoad and hx-on:htmx:after-request, but neither worked. I confirmed that the jQuery code to close the modal is correct by pasting it into Developer Tools. (I'm on Bootstrap 4).
I found an answer.
I removed hx-on:htmx:after-on-load="$('#edit-vendor-modal').modal('hide');"
Instead I return a HX-Trigger header in my response like this (C# code):
Response.Headers.Append("HX-Trigger", "close-active-modal");
return NoContent();
This will cause HTMX to emit an event which you can handle in JavaScript.
Then I have a bit of javascript to handle the event. I wish I did not have to do this as the whole point of HTMX (for me) is to handle common AJAX patterns without custom JS. At least I only need a few lines of JS and this can be reused.
window.addEventListener("load", function () {
document.body.addEventListener("close-active-modal", function () {
$('.modal').modal('hide');
});
});
I had a similar use case: a form inside a bootstrap modal, which should be closed after submission. The server sends 204/NoContent on success.
I managed it with a tiny amount of script inside the markup itself:
<form hx-post="..."
hx-swap="none"
hx-on:htmx:after-request="
if (event.detail.xhr.status === 204)
bootstrap.Modal.getInstance('#my-modal').hide()
">
I prefer this more generic approach though:
<form hx-post="..."
hx-swap="none"
hx-on:htmx:after-request="
if (event.detail.successful)
bootstrap.Modal.getInstance(this.closest('.modal')).hide()
">
If the submission fails then you could handle that in a separate if block, or use a different event like htmx:responseError.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With