Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Feature Request] Dedicated AJAX success event htmx:responseSuccess #3198

Open
lonix1 opened this issue Feb 19, 2025 · 1 comment
Open

[Feature Request] Dedicated AJAX success event htmx:responseSuccess #3198

lonix1 opened this issue Feb 19, 2025 · 1 comment

Comments

@lonix1
Copy link

lonix1 commented Feb 19, 2025

PROBLEM

If an error occurs during an ajax request, we can use htmx:responseError to handle it:

hx-on:htmx:response-error="handleError()"

But there isn't a corresponding event for a success case. One could use this workaround:

hx-on:htmx:after-request="if (event.detail.successful) handleSuccess()"

That's acceptable for trivial cases, but gets very messy and hard to maintain when more branching logic is required.

These are the related events, but they are for the "error" or "error-or-success" cases:

  • htmx:afterOnLoad This event is triggered after an AJAX onload has finished. Note that this does not mean that the content has been swapped or settled yet, only that the request has finished.
  • htmx:afterRequest This event is triggered after an AJAX request has finished either in the case of a successful request (although one that may have returned a remote error code such as a 404) or in a network error situation.
  • htmx:responseError This event is triggered when an HTTP error response occurs

SOLUTION

It would be cleaner to have a "success case" event, e.g. htmx:responseSuccess.

That would be simpler and we could use different handlers for different responses, instead of one mega handler with ugly branching logic (or worse, doing it in a script file).

@scrhartley
Copy link
Contributor

I assume you could set that up yourself and use hx-on:response-success:

<script>
  document.addEventListener('htmx:afterRequest', function(evt) {
    if (evt.detail.successful) {
      htmx.trigger(evt.target, 'responseSuccess', evt.detail)
    }
  })
</script>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants