imacrayon / alpine-ajax

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

Add `x-target` response code modifiers #78

Closed imacrayon closed 3 months ago

imacrayon commented 3 months ago

This PR adds x-target modifiers you can use to change targets based on the response code returned from the server:

<form id="my_form" x-target x-target.302="_self" x-target.500="critical_error" action="/update" method="patch">

This form will only update itself when submitted, with two exceptions:

  1. If the server responds with a 302 status, the browser will perform a full page navigation to the new content
  2. If the server responds with a 500 status, Alpine AJAX will target an element with ID critical_error instead of my_form

You can match a whole class of status codes using the wildcard syntax: x-target.4xx will match any 400 class status.

You can also match both 400 and 500 class status codes using the special error modifier: x-target.error.

This PR also adds two new events for handling responses and requests: ajax:send and ajax:sent.

ajax:send fires just before a fetch call is made, $event.detail contains all of the options that will be passed to fetch so that you can override anything.

ajax:sent fires after a fetch call is made to complement the send event. $event.detail contains the response data from the request.

Resolves #73, #76