HTMX Requests


November 6, 2023

Starting with Toolbox 1.4.0 you can enqueue the HTMX javascript library and register AJAX requests using Twig templates. But what are they?

Dynamic content

If you’ve ever tried to register an AJAX call in WordPress, you know what a pain it can be to simply return a partial layout. You need to add an action-hook with the right name, determine if you want to render it for both private and non-private calls and make sure that it is executed correctly. Using Toolbox, you can do all that with just a few keywords.

Using Twig headers

If you’ve been experimenting with Toolbox before and have used Toolbox to register ACF Blocks, then you’ll probably find this just as easy to use. By adding just a few headers to your twig template, all work is taken out of your hands.

Let’s create this template for instance, using the Twig Templates in your Dashboard:

  TemplateType: htmx
  Action: my-first-html-request
  Privacy: priv nopriv
<h3>This seems to be working</h3>

The headers will tell Toolbox to register an action hook for both a ‘wp_ajax_my-first-html-request’ and ‘wp_ajax_nopriv_my-first-html-request’ so that it works for both logged in and not logged in users.

Using the HTMX Library

HTMX is a library that allows you to access modern browser features directly from HTML, rather than using javascript. It makes it possible to do extraordinary stuff using AJAX calls.

Go to “Settings > Toolbox > 3rd Party CSS/JS” on your WordPress Dashboard and check “Load HTMX JS” so that it is active. This will automatically load the HTMX library on frontend.

Using the HTMX request on a page

Let’s use the HTMX template you created before in a regular page. Create a new page and add a Timber Posts Module and add the following Twig template:

  hx-get="{{ ADMIN_AJAX_URL ~ '?action=my-first-html-request' }}" 

This will ensure that on (hx-trigger) load it will (hx-get) call out to a URL using a GET request and (hx-swap) use a method where it replaces the entire outer HTML content with the results. This means it replaces the div that triggers the call with whatever is being sent back.

Be sure to use the global variable ADMIN_AJAX_URL to ensure you always use the right path for your server.

If all goes well, after saving your page you should see the word ‘loading…’ briefly on screen, after which it calls out to the registered AJAX call and replaces the contents.