Skip to content

Commit

Permalink
ajax helper with no source or target defaults to body (#2948)
Browse files Browse the repository at this point in the history
  • Loading branch information
MichaelWest22 authored Oct 20, 2024
1 parent 3e265ea commit 816fe6d
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 2 deletions.
4 changes: 2 additions & 2 deletions src/htmx.js
Original file line number Diff line number Diff line change
Expand Up @@ -3905,9 +3905,9 @@ var htmx = (function() {
})
} else {
let resolvedTarget = resolveTarget(context.target)
// If target is supplied but can't resolve OR both target and source can't be resolved
// If target is supplied but can't resolve OR source is supplied but both target and source can't be resolved
// then use DUMMY_ELT to abort the request with htmx:targetError to avoid it replacing body by mistake
if ((context.target && !resolvedTarget) || (!resolvedTarget && !resolveTarget(context.source))) {
if ((context.target && !resolvedTarget) || (context.source && !resolvedTarget && !resolveTarget(context.source))) {
resolvedTarget = DUMMY_ELT
}
return issueAjaxRequest(verb, path, resolveTarget(context.source), context.event,
Expand Down
10 changes: 10 additions & 0 deletions test/core/api.js
Original file line number Diff line number Diff line change
Expand Up @@ -278,6 +278,16 @@ describe('Core htmx API test', function() {
div.innerHTML.should.equal('foo!')
})

it('ajax api falls back to targeting body if target and source not set', function() {
this.server.respondWith('GET', '/test', 'foo!')
var div = make("<div id='d1'></div>")
const saveBody = document.body.innerHTML
htmx.ajax('GET', '/test', {})
this.server.respond()
document.body.innerHTML.should.equal('foo!')
document.body.innerHTML = saveBody
})

it('ajax api works with swapSpec', function() {
this.server.respondWith('GET', '/test', "<p class='test'>foo!</p>")
var div = make("<div><div id='target'></div></div>")
Expand Down

0 comments on commit 816fe6d

Please sign in to comment.