bigskysoftware / htmx

</> htmx - high power tools for HTML
https://htmx.org
Other
37.64k stars 1.27k forks source link

ws-send does not send submit button name and value #1337

Open medihack opened 1 year ago

medihack commented 1 year ago

This issue is very similar to #1132, but when using the HTMX WebSockets extension. When a form is sent to the server using WebSocket extension by pressing a submit button (regardless of inside or outside the form), its name and value are not transmitted.

medihack commented 1 year ago

I investigated a bit further and think the problem is that initButtonTracking is only called when an htmx attribute is on the form itself. But according to the documentation hx-ext="ws" should be placed outside the form.

medihack commented 1 year ago

And finally two (a bit ugly) workarounds:

  1. Add the hx-ext="ws" directly on the form element

    <form id="form" hx-ext="ws" ws-connect="/chatroom" ws-send>
    <div id="notifications"></div>
    <div id="chat_room">
        ...
    </div>
    <input name="chat_message">
    </form>
  2. Put an additional empty hx-ext attribute on the form (this makes sure that initButtonTracking is called, see above).

    <div hx-ext="ws" ws-connect="/chatroom">
    <div id="notifications"></div>
    <div id="chat_room">
        ...
    </div>
    <form id="form" hx-ext ws-send>
        <input name="chat_message">
    </form>
    </div>
1cg commented 1 year ago

@Renerick any thoughts?

Renerick commented 1 year ago

WS extensions uses htmx's method for gathering input data. Buttons with type submit are not included. I don't think that changing this on the extension level is a good idea.

As for initButtonTracking and ws-ext workaround, I'll investigate further, what's going on there

medihack commented 1 year ago

It should somehow (on the server) be distinguished which button was pressed. The workaround works because initButtonTracking is called in initNode which is only called on elements that have an attribute of kind [hx-sse], [data-hx-sse], [hx-ws], [data-hx-ws], [hx-ext], [data-hx-ext]. I hope this helps with the investigation.

Renerick commented 1 year ago

Yup, can confirm

To fix this issue htmx would have to expose initButtonTracking in the internal API, so extensions could enable this feature whenever needed. If it's ok, I can work on this. It's a quick and simple fix, but adding another internal API method seems a bit too much.

Alternatively, we would have to come up with more automatic way of finding forms with buttons that need tracking, but I'm failing to produce a robust solution right now

Scanning DOM for closest parent forms of input[type=submit, name, value],button[type=submit, name, value] seems promising, but I imagine there would be many edge cases

Making an attribute like hx-track-button is also an option, of course, but this is definitely not a solution I would like to have