
- HTMX - Home
- HTMX - Introduction
- HTMX - Installation
- HTMX - Features
- HTMX - Attributes
- HTMX - Ajax
- HTMX - Inheritance
- HTMX - Boosting
- HTMX - Websockets
- HTMX - Server Sent Events(SSE)
- HTMX - History Support
- HTMX - Requests
- HTMX - Responses
- HTMX - Validation
- HTMX - Animations
- HTMX - Extensions
- HTMX - AI Extension
- HTMX - Events
- HTMX - Logging
- HTMX - Debugging
- HTMX - Scripting
- HTMX - 3rd Party Integration
- HTMX - Caching
- HTMX - Security
- HTMX - Configuring
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