The bookkeeping API Mrs. Rini uses only accepts JSON. Your htmx form sends name=Mrs.%20Tini&weight=4, and the API turns it down. htmx itself has no attribute for changing the body's format. What does: an extension.
An extension is an add-on that gives htmx a new ability without changing its core: sending a form as JSON, putting error replies in another box, loading a page before it's clicked. In htmx 2, every extension is its own package named htmx-ext-.... It goes in in two steps: loaded with a <script> tag after htmx, then switched on with hx-ext on the element that uses it. It's like the washing machine accessories at Mrs. Rini's Laundry. An extra dryer has to be bought and fitted first (the script), then switched on for the machine that should use it (hx-ext). Pressing the dryer button on a machine that never got one does nothing.
Installing an extension: load, then switch on
<script src="https://unpkg.com/[email protected]"></script>
<script src="https://unpkg.com/[email protected]"></script>
<script src="https://unpkg.com/[email protected]"></script>
<body hx-ext="response-targets">
<form hx-post="/order" hx-ext="json-enc">...</form>
</body>
- htmx first, then the extension. An extension's script calls
htmx.defineExtension(...), so if htmx isn't loaded yet, the Console sayshtmx is not defined. hx-extis inherited by everything inside. Several at once are separated by commas:hx-ext="json-enc, response-targets".hx-ext="ignore:json-enc"switches one off for that part.- A name in
hx-extthat htmx doesn't know is ignored with no error. So without its script, the form is still sent form-encoded as usual. - The old htmx 1 address,
htmx.org/dist/ext/json-enc.js, still exists in the htmx 2 package, but it holds the htmx 1 version of the extension and the Console prints a warning. Use thehtmx-ext-...packages. - With Vite (in Laravel, say):
npm install htmx-ext-json-enc, thenimport 'htmx-ext-json-enc'after htmx.
json-enc: send the form as JSON
<form id="intake" hx-post="/order" hx-ext="json-enc" hx-target="#order-board" hx-swap="beforeend">
<input name="name" value="Mrs. Tini">
<input name="weight" value="4">
<label><input type="checkbox" name="service" value="ironing" checked> Ironing</label>
<label><input type="checkbox" name="service" value="folding" checked> Folding</label>
<button>Take in laundry</button>
</form>
| Without json-enc | With json-enc | |
|---|---|---|
Content-Type |
application/x-www-form-urlencoded |
application/json |
| Body | name=Mrs.%20Tini&weight=4&service=ironing&service=folding |
{"name":"Mrs. Tini","weight":"4","service":["ironing","folding"]} |
weightstays text,"4", because form values are always text. Values fromhx-valskeep their type:hx-vals='{"express": true}'becomes"express":true.- A name that appears twice becomes an array:
"service":["ironing","folding"]. - Only the body changes. A GET request still puts its values in the address.
- Laravel reads JSON the same way as a form:
$request->input('name'). json-enc is useful for an API that only accepts JSON.
response-targets: error replies into another box
From the validation lesson: htmx 2 doesn't swap 4xx and 5xx replies. response-targets gives each status a target of its own:
<body hx-ext="response-targets">
<div id="error"></div>
<form id="intake" hx-post="/order" hx-target="#order-board" hx-swap="beforeend"
hx-target-422="#error">
...
</form>
<ul id="order-board">...</ul>
</body>
| The server's reply | Lands in |
|---|---|
201, <li id="order-15">...</li> |
#order-board, as usual |
422, <p>Only 20 kg of room is left today.</p> |
#error |
| 500 with no rule | not swapped |
- The attribute name patterns:
hx-target-422exactly,hx-target-4*(or4xx) for every 4xx,hx-target-5*, andhx-target-errorfor every 4xx and 5xx. - Put
hx-ext="response-targets"on an element that holds the target too, such as<body>. This extension works at swap time, on the target element. On the form alone, with#order-boardoutside the form, its rules don't run. - The difference from
responseHandling(the validation lesson):responseHandlingswaps the 422 into the same target, response-targets sends it to another box.
preload: start loading before the click
<body hx-ext="preload">
<button hx-get="/report" hx-target="#report" preload="mouseover">Today's report</button>
- By default
preload(with no value) starts loading when the mouse button is pressed, 100 to 200 ms before the click completes.preload="mouseover"starts after the cursor rests 100 ms on it. On a touch screen, when it's touched. - The preload request carries the header
HX-Preloaded: true. Its reply is kept in the browser cache, so the real click takes it from the cache, as long as the server allows it, for exampleCache-Control: private, max-age=60. - Example: the server needs 400 ms. The cashier points at the button 600 ms before clicking. Without preload, the report shows 400 ms after the click. With
preload="mouseover", the reply is already in the cache, so it shows as soon as it's clicked. - Only for GET (links and
hx-get). POST and DELETE are never preloaded.
loading-states: indicators through data-loading
<style>[data-loading] { display: none; }</style>
<body hx-ext="loading-states">
<form id="intake" hx-post="/order" data-loading-states>
<button data-loading-disable>Take in laundry</button>
<span data-loading>Saving...</span>
</form>
data-loadingshows during the request,data-loading-disablesetsdisabled,data-loading-classadds classes.data-loading-delaywaits 200 ms first, so a fast reply doesn't make the indicator flicker.data-loading-statesfences in its area. Without it, every request on the page, Check status included, also disables the Take in laundry button and shows Saving...- For simple needs,
hx-indicatorandhx-disabled-elt(the loading indicator lesson) are enough with no extension.
One more, good to know: head-support merges the <head> (title, meta, CSS) of a boosted page's reply. Use it when your pages need different CSS or meta tags.
⚠️ Extensions that stay silent, or react in the wrong places
hx-extwithout its script, or a misspelled name. htmx just stays quiet, no error. Check the Network tab: the body is still form-encoded. In the exercise, the page needs<script src="https://unpkg.com/[email protected]">, and the form needshx-ext="json-enc",hx-post="/api/data"and anhx-targetpointing at an id that really exists (#result). The example server only answersReceived as JSONwhen the body really is JSON.- The extension's script before htmx.
htmx is not defined, and the extension never registers. - response-targets on the form only. A target outside the form isn't covered, so the 422 still isn't swapped. Put
hx-exton<body>. - loading-states without
data-loading-states. Every indicator on the page reacts to every request.
TL;DR: In htmx 2, an extension is its own htmx-ext-... package: load its script after htmx, then switch it on with hx-ext (inherited, comma separated, ignore: to switch off). Without its script, hx-ext is ignored silently. json-enc sends the body as application/json ({"name":"Mrs. Tini","weight":"4"}). response-targets puts a reply in another target per status (hx-target-422="#error", hx-target-error), with hx-ext on an element that also holds the target. preload loads a GET early when the mouse button is pressed or the cursor rests 100 ms, and needs caching the server allows. loading-states uses data-loading, data-loading-disable and data-loading-delay, fenced in with data-loading-states. head-support merges the <head> of boosted pages.
⚡ Load first, then switch on
Write:
<script src="https://unpkg.com/[email protected]"></script>
<script src="https://unpkg.com/[email protected]"></script>
<script src="https://unpkg.com/[email protected]"></script>
<body hx-ext="response-targets">
<form hx-post="/order" hx-ext="json-enc">...</form>
</body>
Guess first: hx-ext="json-enc" is written, but its script was never loaded. What happens?
No error. htmx ignores a name it doesn't know, and the form is still sent form-encoded as usual.
Meaning: htmx's script first, then the extension's. Then hx-ext switches it on for the element that uses it, and it's inherited by everything inside.
⚡ json-enc: send the form as JSON
Meaning: The body name=Mrs.%20Tini&weight=4 becomes {"name":"Mrs. Tini","weight":"4"}, with Content-Type: application/json. weight stays text, because form values are always text.
⚡ response-targets: error replies into another box
Meaning: hx-target-422="#error" puts a 422 reply in #error, not in the usual target. Put hx-ext="response-targets" on an element that also holds the target, such as <body>.