Skip to content

Instantly share code, notes, and snippets.

@niladam
Forked from newtonjob/form.js
Created February 2, 2026 09:08
Show Gist options
  • Select an option

  • Save niladam/aaf62b7b5641f514328cf5a7409aa243 to your computer and use it in GitHub Desktop.

Select an option

Save niladam/aaf62b7b5641f514328cf5a7409aa243 to your computer and use it in GitHub Desktop.
Form plugin for Alpine.js
document.addEventListener('alpine:init', () => {
Alpine.magic('form', el => () => {
return Alpine.reactive({
processing: false,
recentlySuccessful: false,
errors: {},
submit() {
return axios.post(el.action, el).then(response => {
this.errors = {};
this.recentlySuccessful = true;
this.dispatch('success', response.data);
setTimeout(() => this.recentlySuccessful = false, 3000);
return Promise.resolve(response.data);
}).catch(({ response }) => {
this.dispatch('error', response);
this.errors = response.data.errors ?? {};
return Promise.reject(response);
}).finally(() => this.dispatch('finish'));
},
dispatch(event, data) {
el.dispatchEvent(new CustomEvent(event, { detail: data, bubbles: true }));
},
});
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment