-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathform.js
37 lines (32 loc) · 948 Bytes
/
form.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
const form = document.querySelector('[data-form]');
const onSuccess = (response) => {
const node = document.createElement('div');
node.classList.add('text-green-500');
node.innerHTML = `Thank you for your message.`;
form.appendChild(node);
}
const handleSubmit = event => {
event.preventDefault()
const formData = new FormData(form)
const action = form.dataset.actionUrl
// Send the form data to the API
fetch(action, {
method: "POST",
headers: { "Content-Type": "application/x-www-form-urlencoded" },
body: new URLSearchParams(formData).toString(),
})
.then(response => {
return response
})
.then(response => {
if (response.ok) {
onSuccess(response)
// Clear the form
form.reset()
}
})
.catch(error => {
console.error("Error:", error)
})
}
form?.addEventListener("submit", handleSubmit)