HTMX - Responses



The primary way HTMX handles responses is by updating the target element with the content returned from the server.

  • HTML: The most common response type, directly inserted into the target element.
  • Plain text: Inserted as a text content.
  • JSON: Can be used with the HX-Reswap header to control how the content is inserted.

Response Headers

HTMX recognizes several special response headers that can control its behavior.

  • HX-Trigger: Triggers client-side events.
  • HX-Refresh: If "true", triggers a full page refresh.
  • HX-Redirect: Triggers a client-side redirect.
  • HX-Reswap: Controls how the response content is swapped in.

Example: This is a server-side code.

from flask import make_response

@app.route('/submit', methods=['POST'])
def submit():
    response = make_response("
Success!
") response.headers['HX-Trigger'] = 'showMessage' return response

Error Handling

HTMX provides built-in error handling. By default, it will swap any content returned on an error into the target element. You can also listen for the htmx:responseError event to handle errors more specifically.

document.body.addEventListener('htmx:responseError', function(evt) {
    alert('There was an error: ' + evt.detail.error);
  });
Advertisements