Search code examples
javascripthtmlhtmx

how to swap the response in the DOM using HTMX when it's 4xx or 5xx response HTTP status codes?


I'm trying to do the next using HTMX:

<form hx-boost="true" hx-target="#response" hx-swap="afterbegin">
    <label for="title">Title of your post</label>
    <input type="text" id="title" name="title">
    <button type="submit">Send post</button>
</form>
<div id="response">
    <!-- Here goes the response from the server -->
</div>

In the server, the internal logic is:

When the title of the post is empty returns some div with a message that indicates an error in the request and also responds with a 400 HTTP status code, but when I do all of that, the response isn't beign swapped (of course if the HTTP status is 200, anything that comes from the server is swapped in).

I tried something curious and it's, if you disable javascript in the browser, the page is full reloaded and loads the div correctly.

It's not a Content-Type header error because the CT header is text/html; charset=utf-8 when the server responds


Solution

    1. HTMX need additional script to work with error response, you can add this <script src='https://unpkg.com/htmx.org/dist/ext/response-targets.js'></script>, along with your HTMX script.
    2. You must wrap with outer element using attributte hx-ext="response-targets".
    3. Use hx-target-4xx or hx-target-5xx attributes to work with error response.

    Your code should be working if it's like this:

    <div hx-ext='response-targets'>
      <form hx-boost="true" hx-target="#response" hx-target-4xx='#errorResponse' hx-swap="afterbegin">
          <label for="title">Title of your post</label>
          <input type="text" id="title" name="title">
          <button type="submit">Send post</button>
      </form>
      <div id="response">
          <!-- Here goes the response from the server -->
      </div>
      <div id="errorResponse">
          <!-- Here goes the error response from the server -->
      </div>
    </div>