Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ajax helper with no source or target defaults to body #2948

Merged
merged 1 commit into from
Oct 20, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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