htmx icon indicating copy to clipboard operation
htmx copied to clipboard

Using htmx.ajax and hx-target

Open Benoss opened this issue 3 years ago • 5 comments

I am triggering htmx.ajax but my response contains a full page and I am trying to swap a part of the response What I am doing is working but seems really silly is there a cleaner way to do it?

  function swap_htmx(target, something) {
    var doc = document.createElement('html');
    doc.innerHTML = something.xhr.responseText
    target.replaceWith(doc.querySelector("#inner-page"))
  }

htmx.ajax('GET', new_url, {source: "#inner-page", handler:swap_htmx})
window.history.pushState({}, '', new_url);

Another solution would be to configure properly the element "#inner-page" using the hx- markup and trigger an event, but I can't find a way to replace the value of hx-get. I used setAttribute but seems to be ignored

<div class="lg:w-98% w-75% flex flex-col gap-8 relative" id="inner-page" hx-trigger="filter-event" hx-target="this" hx-swap="outerHTML" hx-push-url="true">
old data
</div>

    let inner = htmx.find("#inner-page")
    inner.setAttribute("hx-get", new_url)
    htmx.trigger(inner, "filter-event")

Thanks for your help

Benoss avatar Dec 03 '21 07:12 Benoss

@Benoss -- Your second solution is the better way to go, with one small change. If you're dynamically changing the value of hx-get, you need to tell htmx about the change. Put htmx.process(node) at the end of your Javascript and it should update correctly.

@1cg -- Unless we're changing event handlers that are registered via hx-trigger I don't see why htmx couldn't just look up the action (hx-get, hx-post, hx-delete, hx-put) dynamically when the element is activated. It might even save a small amount of up-front processing. Is there a reason this needs to be scanned and cached ahead of time?

benpate avatar Dec 09 '21 03:12 benpate

Agree w/ you ben, no reason to aggressively cache the request URL. But I think the crux here is that the htmx.ajax() function needs more functionality. We need to include a select option, just like we have a target option:

https://htmx.org/api/#ajax

I'll add it to the list

1cg avatar Jan 16 '22 22:01 1cg

@1cg, are there any plans to implement select option of htmx.ajax() in the near future? Definitely a useful thing, it would simplify the writing of a server-side HTML render function.

applecat avatar Nov 08 '22 09:11 applecat

Can we get the select select option added in htmx.ajax?

mardix avatar Dec 21 '22 15:12 mardix

@1cg

I ran into this issue where I needed "select" on the ajax javascript function a couple days ago and wouldn't mind taking a crack at implementing it. Is it still on the list of things that need doing?

ece-jacob-scott avatar Nov 09 '23 02:11 ece-jacob-scott