htmx

htmx: hx-target: swap html vs full page reload


I have a page containing several forms.

If a user submits a form, then only the current form should get submitted (not the other forms of the page).

On the server the form gets validated.

Case 1: If validation failed, then the server sends html to the client and the particular form should get swapped and the new form should be added to the DOM. This new form contains an error message. The user can now fix his mistake an submit the form again.

Case 2: The form validation was successful, the data got saved. Now I want to trigger a full-page redirect on the client.

I read the docs of htmx hx-target. I managed to get case-1 working (I like this feature of htmx).

But how can the server trigger a full-page redirect?


Solution

  • I found this:

    you can use the HX-Redirect http response header to trigger a redirect on the client.

    I create this class for my Django based application. This way a snippet can trigger a reload of the whole page:

    
    class HTTPResponseHXRedirect(HttpResponseRedirect):
        def __init__(self, *args, **kwargs):
            super().__init__(*args, **kwargs)
            self['HX-Redirect']=self['Location']
        status_code = 200