Debian Codegraph @

www/src/content/reference/05-methods/01-htmx-ajax.md

raw symbols SCIP
1 ---
2 title: "htmx.ajax()"
3 description: "Issues an htmx-style ajax request"
4 ---
5
6 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.
7
8 ## Syntax
9
10 ```javascript
11 htmx.ajax(method, url, element) // swap target is a DOM element
12 htmx.ajax(method, url, selector) // swap target is a CSS selector string
13 htmx.ajax(method, url, context) // full context object
14 ```
15
16 ## Parameters
17
18 - `method` - HTTP method (GET, POST, PUT, PATCH, DELETE)
19 - `url` - URL to request
20 - `element` - A DOM element to use as the swap target
21 - `selector` - A CSS selector string identifying the swap target
22 - `context` - A configuration object with the following fields:
23 - `source` - the source element of the request
24 - `event` - an event that triggered the request
25 - `handler` - a callback that will handle the response HTML
26 - `target` - the target to swap the response into
27 - `swap` - how the response will be swapped in relative to the target
28 - `values` - values to submit with the request
29 - `headers` - headers to submit with the request
30 - `select` - allows you to select the content you want swapped from a response
31 - `selectOOB` - allows you to select content for out-of-band swaps from a response
32
33 ## Return Value
34
35 Returns a `Promise` that resolves after the content has been inserted into the DOM.
36
37 ## Examples
38
39 ```javascript
40 // Swap target as a CSS selector
41 htmx.ajax('GET', '/example', '#result')
42
43 // Full context object
44 htmx.ajax('GET', '/example', {
45 target: '#result',
46 swap: 'innerHTML'
47 })
48
49 // Promise-based callback after insertion
50 htmx.ajax('GET', '/example', '#result').then(() => {
51 console.log('Content inserted successfully!');
52 })
53 ```