Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call htmx:after-on-load after successful hx-post

Tags:

htmx

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).

like image 724
Jess Avatar asked Nov 15 '25 11:11

Jess


2 Answers

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');
    });
});
like image 138
Jess Avatar answered Nov 16 '25 23:11

Jess


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.

like image 44
lonix Avatar answered Nov 17 '25 00:11

lonix



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!