Redirects: _redirect(), _location(), _refresh() htmx

Send htmx to another page (HX-Redirect), load a page into the current one without a reload (HX-Location), or reload (HX-Refresh).

_class('htmx')->_redirect($url)
_class('htmx')->_redirect_login()
_class('htmx')->_location($url)
_class('htmx')->_refresh()

Options

OptionMeaning
_redirect($url)HX-Redirect: htmx changes window.location (a full page load).
_redirect_login()HX-Redirect: /login/.
_location($url_or_array)HX-Location: an ajax load of the page, history updated; an array (['path', 'target', 'select', 'swap']) is sent as JSON.
_refresh()HX-Refresh: true: htmx reloads the page.
SEND_HEADERS, EXIT_AFTER_HEADERfalse / false record the lines in sent_headers and return instead of ending the request (tests).

Example

HX-Location loads here.

Code

$hx = _class('htmx');
$self = url('/@object/htmx/redirect');
if ($hx->_wants_fragment()) {
    match ($_GET['hx'] ?? '') {
        'redirect' => $hx->_redirect(url('/@object/htmx/overview')),
        'location' => $hx->_location(['path' => url('/@object/htmx/fragment'), 'target' => '#docs-ref-hx-loc', 'select' => '.docs-ref-live']),
        'refresh' => $hx->_refresh(),
        default => null,
    };
}
asset('htmx');
$button = fn ($hx_value, $text) => '<button type="button" class="btn btn-default btn-outline-secondary" hx-get="' . _prepare_html($self) . '" hx-vals=\'{"hx": "' . $hx_value . '"}\'>' . $text . '</button> ';
return '<p>' . $button('redirect', 'HX-Redirect to the overview') . $button('location', 'HX-Location: the fragment page below') . $button('refresh', 'HX-Refresh this page') . '</p>'
    . '<div id="docs-ref-hx-loc" class="well">HX-Location loads here.</div>';

Notes

  • Each helper turns graphics off and ends the request: call it last, on the htmx answer only (never while a page renders). _redirect_login() is _redirect('/login/').
  • The URL comes from site code; redirect targets are not checked here.
  • For the redirects of the framework itself (redirect()->_go() after a POST, a logged-out admin) see HX-Redirect and HX-Refresh.

See also: htmx/framework_redirects, demo:htmx/redirect