The htmx.ajax() function issues an AJAX request with htmx semantics. It returns a Promise that resolves after the response content has been inserted into the DOM, allowing you to chain callbacks.
Syntax
htmx.ajax(method, url, element) // swap target is a DOM element htmx.ajax(method, url, selector) // swap target is a CSS selector string htmx.ajax(method, url, context) // full context object
Parameters
method- HTTP method (GET, POST, PUT, PATCH, DELETE)url- URL to requestelement- A DOM element to use as the swap targetselector- A CSS selector string identifying the swap targetcontext- A configuration object with the following fields:source- the source element of the requestevent- an event that triggered the requesthandler- a callback that will handle the response HTMLtarget- the target to swap the response intoswap- how the response will be swapped in relative to the targetvalues- values to submit with the requestheaders- headers to submit with the requestselect- allows you to select the content you want swapped from a responseselectOOB- allows you to select content for out-of-band swaps from a response
Return Value
Returns a Promise that resolves after the content has been inserted into the DOM.
Examples
// Swap target as a CSS selector htmx.ajax('GET', '/example', '#result') // Full context object htmx.ajax('GET', '/example', { target: '#result', swap: 'innerHTML' }) // Promise-based callback after insertion htmx.ajax('GET', '/example', '#result').then(() => { console.log('Content inserted successfully!'); })