js
js
TTCTheo's Typesafe Cult
Created by js on 1/17/2024 in #questions
HTMX: script `hx-on::before-request` didn't finish before sending AJAX request
so I am playing with HTMX + Laravel. https://htmx.org/ https://laravel.com/docs/10.x I have this cart form to submit. And it needs to follow browser localStorage. So I use hx-on::before-request to generate a new hidden input according to the current localStorage before submitting. On the first click (even if there's something in the localStorage), the server side couldn't get the hidden input. After it's generated (on the first time), the following clicks (taking input from the cart generated on the first time) work and the server side get the hidden input. I have tried replacing hx-on::before-request with hx-on::before-send, it gives the same result. https://htmx.org/events/#htmx:beforeRequest https://htmx.org/events/#htmx:beforeSend My guess is the hidden input isn't generated yet before the first AJAX request was sent to the server. Because I manually inserted the same hidden and it works too. But I have no idea how to properly solve this issue (not hacking) Any help would be appreaciated. Cheers
<form
id="add-{{ $product->slug }}"
hx-patch="/cart/inc/{{ $product->slug }}"
hx-on::before-request="updateCart(); genTmpCart('form#add-{{ $product->slug }}');"
hx-on::after-request="updateLocalStorage();"
>
<button class="product-card__add-to-cart-btn">
Add to cart
</button>
</form
<form
id="add-{{ $product->slug }}"
hx-patch="/cart/inc/{{ $product->slug }}"
hx-on::before-request="updateCart(); genTmpCart('form#add-{{ $product->slug }}');"
hx-on::after-request="updateLocalStorage();"
>
<button class="product-card__add-to-cart-btn">
Add to cart
</button>
</form
4 replies