htmx
htmx copied to clipboard
HX-Redirect: how to do a full redirect and avoid hx-target?
Consider this common form validation pattern:
- I have a form that gets posted to the server.
- If form validation occurs, just return the
- If form is valid, perform whatever server-side action and then redirect to another page.
So I have a form like this:
<form class="rounded border bg-white mb-3"
id="article-form"
method="post"
hx-post="/post-url/"
hx-target="this">
The server returns the form HTML correctly with errors. However, when sending a redirect, the whole page is loaded into the form tag (given the hx-target).
To get around this I've tried setting the HX-Redirect and HX-Refresh headers in the response, but neither appear to have any effect: the content is still loaded into the hx-target element.
Is there an idiomatic way to do this with htmx, or do I just have to go back to full server-side page reloads for validation?
Rather than sending a server-side redirect back, you should use the HX-Redirect response header. If this doesn't work then please provide a simple example so that we can replicate and debug. Also, please ensure you're on the latest version of htmx.
As I mentioned, I tried the hx-redirect header. Should the response status be 200?
Yes, it should.
Two thoughts here:
-
If you send an
HX-Redirectheader, you want just a normal 200 response code because the redirect is going to be done server side. -
It sounds like you want to replace a different target on success. Would the OOB swap mechanism be acceptable for this? https://htmx.org/docs/#oob_swaps
We could add a new header, HX-Retarget that allows you to change the target of the response via the header. Worth considering.
From what I see in the latest changelog, HX-Retarget seems to be implemented.
https://github.com/bigskysoftware/htmx/blob/master/CHANGELOG.md#161---2021-11-22
Does it mean this issue can be closed?
From what I see in the latest changelog,
HX-Retargetseems to be implemented.https://github.com/bigskysoftware/htmx/blob/master/CHANGELOG.md#161---2021-11-22
Does it mean this issue can be closed?
I don't think Retarget is relevant for what the OP wanted to do. But their (and my) issue is solved by having the server send the response with status 200 when including a HX-Redirect header. So I think this issue can indeed be closed.
EDIT: See the discussion in https://github.com/bigskysoftware/htmx/issues/632 for more info on why the behaviour is the way it is.
closing, yes, this appears to be addressed