How to implement a redirect with HTMX?
Asked Answered
D

3

11

HTMX is great and using AJAX for most of the stuff is awesome! But from time to time I just need a real "phyiscal" redirect to another page.

Any ideas how to achieve this without starting to write custom JS code?

Thx!

Deil answered 7/1, 2022 at 7:59 Comment(0)
D
22

Luckily, after googleing for ages I found this post at Reddit: https://www.reddit.com/r/htmx/comments/ot6kai/comment/h6v5cn9/?utm_source=share&utm_medium=web2x&context=3

You can easily set the HX-Redirect header in your backend and on the return of the response, your browser will magically redirect.

The docs state this here but unfortunately don't explain it in more detail on other pages.

Supplemantal: I experienced an issue with JS errors occuring after the redirect - even though everything works fine.

Deil answered 7/1, 2022 at 7:59 Comment(1)
I used this reddit and it was very useful for me. Only if you are using Django: reddit.com/r/htmx/comments/s36zx2/how_do_you_use_hxredirectSasin
V
1

A solution I've found is to return a meta tag, as it has the ability to refresh the page (or redirect to a new page) after set amount of seconds.

Refresh the page 5 seconds after html loads:

<div><meta http-equiv="refresh" content="5"></div>

Redirect to a new page 0 seconds after html loads:

<div><meta http-equiv="refresh" content="0; url=/new-page/"></div>

Delaying the page redirect could be useful if you want to show a success animation or something before redirecting.

Vastah answered 31/1 at 12:58 Comment(0)
V
0

I'm just starting to learn Golang & HTMX at the same time. This is how I am handling a redirect after deleting a contact.

The user visits http://localhost:8080/contacts/3/edit. User clicks Delete Contact button:

<form hx-post="/contacts/{{.Id}}/delete" hx-target="body">
  <button id="delete-btn" type="submit">Delete Contact</button>
</form>

This is the handler for http.HandleFunc("POST /contacts/{id}/delete", deleteContact):

func deleteContact(w http.ResponseWriter, r *http.Request) {
    id, err := strconv.Atoi(r.PathValue("id"))
    if err != nil {
        log.Println(err)
    }
    contacts.delete(id) 

    // There is some error checking & logic redacted here for simplicity.

    w.Header().Add("Hx-Redirect", "/contacts")
}

This is giving me the result I am expecting. The client is redirected to /contacts, the browser URL is also updated, and the updated list of contacts is displayed. There are no JS errors in the browser console.

Vanadium answered 24/8 at 17:21 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.