Search code examples
alpine.jshtmx

update alpine.js data variable on htmx form submit response


I'm using HTMX and Alpine.js on a form like

<form x-data="{submitted: false}" @submit.prevent="submitted = true" hx-on:htmx:after-request="submitted = false" hx-post hx-swap="none">

    {% csrf_token %}
    <p x-text="submitted"></p>

    {% include "style-guide/components/input.html" with form=form name="email" label="Email" placeholder="Email" %}

    <div id="password1"></div>

    <button type="submit" class="mt-4 btn bg-gradient-primary w-100" :disabled="submitted">
          Authenticate
      <i x-show="submitted" class="fa-solid fa-spinner fa-spin ms-2"></i>
    </button>
</form>

When the form is submitted, the submitted variable is set to true inside @submit.prevent to disable the button and show the spinner.

I want to set the submitted to false when the HTMX response is complete.

For this I tried using hx-on:htmx:after-request="submitted = false" but this is not working.

Replacing submitted = false with alert('submitted') works fine but the variable is not updating.

How can I update the alipne.js data variable on HTMX event?


Solution

  • htmx can't access to the AlpineJs object and to its properties, but you can intercept the event raised by htmx using AlpineJs and then update the submitted property:

    <form x-data="{submitted: false}"
          @submit.prevent="submitted = true"
          @htmx:after-request.camel="submitted = false"
          hx-post
          hx-swap="none"
    >
    

    The event raised by htmx is htmx:afterRequest and since html attributes are case insensitive, Alpine allows you to specify the event name in the kebab-case but it considers the camel-case when the .camel modifier is used