Search code examples
formswebsockethtmx

HTMX websocket extension not sending form data in message to server


I have this form


<script src="https://unpkg.com/[email protected]" integrity="sha384-D1Kt99CQMDuVetoL1lrYwg5t+9QdHe7NLX/SoJYkXDFfX37iInKRy5xLSi8nO7UC" crossorigin="anonymous"></script>
<script src="https://unpkg.com/htmx.org/dist/ext/ws.js"></script>
<script> htmx.logAll() </script>
<div id="messages" class="h-96 w-48 bg-gray-200 mx-auto "></div>
<div ws-connect="/ws-chat" hx-ext="ws">
    <form id="form" hx-boost="true" ws-send="true" >
        <input ws-send class="mx-auto" id="msg-input" type="text" placeholder="Write a message..."/>
        <button type="submit">Send</button>
    </form>
</div>

When I type something into the input and press Send, or press Enter in the text box, I get the full four messages: wsBeforeSend, wsAfterSend, wsBeforeMessage, wsAfterMessage.

Inside of wsBeforeSend and wsAfterSend, the "message" object is like so: message: '{"HEADERS":{"HX-Request":"true","HX-Trigger":null,"HX-Trigger-Name":null,"HX-Target":null,"HX-Current-URL":"http://localhost:3000/chat"}}'

So it's not adding any of the form data! I just need some help here, I get the same thing back on the return because I have the server echoing what's coming back to me. I see this HTMX GitHub issue about this but I tried both of the solutions they provided as a stop-gap, and it doesn't work, and the issue was closed with a bugfix pr.

Any help is appreciated.


Solution

  • You are missing the name attribute in your input field.

    <input ws-send name="message_input" class="mx-auto" id="msg-input" type="text" placeholder="Write a message..."/>
    

    Once it's added, you should then see your value being attached to the payload:

    {
        "message_input": "foobar",
        "HEADERS": {
            "HX-Request":"true",
            "HX-Trigger":null,
            "HX-Trigger-Name":null,
            "HX-Target":null,
            "HX-Current-URL":"http://localhost:3000/chat"
        }
    }