imacrayon / alpine-ajax

An Alpine.js plugin for building server-powered frontends.
https://alpine-ajax.js.org
MIT License
650 stars 13 forks source link

Multi button form ajax question #108

Open florian-sun opened 2 weeks ago

florian-sun commented 2 weeks ago

This is not an issue, just a request for help. I don't see any Discussions tag so I'm asking here. If this is not appropriate, let me know and I'll delete this post. So here is my setup. I have a form with several buttons, each with its own handler. Each button must do some stuff and then shd perform a different AJAX transformation. Is this possible?

imacrayon commented 2 weeks ago

It might help if you had an example, but yes - you can have multiple buttons in the same form submit to different endpoints.

Using form attribute:

<form method="post" action="/update">
  <button>Update</button>
  <button form="delete_form">Delete</button>
</form>
<form method="post" action="/delete" id="delete_form"></form>

Using formaction/formmethod attributes:

<form method="post" action="/update">
  <button>Update</button>
  <button formaction="post" formmethod="/delete">Delete</button>
</form>

This is just HTML though, nothing to do with Alpine AJAX. Adding x-target to theses forms will issue AJAX requests as expected though.

florian-sun commented 2 weeks ago

Thanks, but, as I said, the buttons have their own handlers already, doing stuff different than submitting the form. So I don't actually want to submit the form, I just want the AJAX functionality. I will provide an example later. I think the $ajax magic can do something about this but it's not clear how to use it

florian-sun commented 2 weeks ago

Here is an example, sort of:

<form x-data="{ f1(){...}, f2(){...} }">
  <button @click="f1()">button1</button> // fetch some html and shd x-target id1
  <button @click="f2()">button2</button> // fetch some html and shd x-target id2
</form>
justisr commented 4 days ago

@florian-sun Christian may have other suggestions, but intuitively, my first approach would be to use the $ajax helper within f1 and f2 to manually perform your Ajax request. https://alpine-ajax.js.org/reference/#ajax

Alternatively, you could have a single function which accepts the endpoint & target as params which you provide in your click handlers.

imacrayon commented 4 days ago

Ah, sorry, I missed your follow up message @florian-sun. But ditto to Justis’s suggestion 👍