_is_hx(), _get_req() htmx

Tell an htmx request from a plain one and read its HX-* headers: is_hx, req[target], req[trigger], req[boosted]...

_class('htmx')->_is_hx()
_class('htmx')->_get_req()

Options

OptionMeaning
is_hxtrue for a request with HX-Request (set by _is_hx() at init).
req[request], req[boosted], req[history_restore_request]The HX-Request, HX-Boosted, HX-History-Restore-Request headers.
req[target], req[trigger], req[trigger_name], req[current_url]Id of the target element, of the element that triggered, its name, the page URL (HX-Current-URL).
target, boostedShortcuts filled at init.

Example

This page request:

{
    "is_hx": false,
    "request": false,
    "boosted": false,
    "target": "",
    "trigger": "",
    "trigger_name": "",
    "current_url": "",
    "history_restore_request": false
}

Code

$hx = _class('htmx');
$facts = fn () => '<pre>' . _prepare_html(json_encode(['is_hx' => $hx->is_hx] + $hx->req, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES)) . '</pre>';
if ($hx->_wants_fragment() && ($_GET['hx'] ?? '') === 'req') {
    return $hx->_result('<p>Seen by the server on the htmx request:</p>' . $facts());
}
asset('htmx');
return '<p>This page request:</p>' . $facts()
    . '<button type="button" class="btn btn-primary" id="docs-ref-hx-req-btn" name="show_request" hx-get="' . _prepare_html(url('/@object/htmx/request')) . '" hx-vals=\'{"hx": "req"}\' hx-target="#docs-ref-hx-req">Send it through htmx</button>'
    . '<div id="docs-ref-hx-req"></div>';

Notes

  • Headers come from the client: use them to pick the answer (fragment or page), never for access decisions.
  • _get_req() and _is_hx() run at init; call them again only if a test changes $_SERVER.

See also: htmx/fragment, htmx/boost