-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy patheasy-form-submit.js
66 lines (60 loc) · 2.13 KB
/
easy-form-submit.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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
/**
* Handles the submission of a form with custom validation and event handling.
*
* @param {string} formID - The ID of the form to be handled.
* @param {Object} options - Configuration options for form submission.
* @param {string} options.submitURL - Custom URL to submit the form. Defaults to FormSubmit.
* @param {string} options.key - Key to use with FormSubmit (if submitURL is not provided).
* @param {Object} options.data - Additional data to send with the form.
* @param {Function} options.validate - Custom validation function that should return a boolean.
* @param {Function} options.onSuccess - Callback function executed if the submission is successful.
* @param {Function} options.onError - Callback function executed if an error occurs.
*/
function easyFormSubmit(formID, options = {}) {
const form = document.getElementById(formID);
// Check if the form exists
if (!form) {
console.error(`Form with ID "${formID}" not found.`);
return;
}
// Add a listener for the 'submit' event
form.addEventListener("submit", async (event) => {
event.preventDefault();
// Custom validation
if (options.validate && !options.validate(form)) {
console.error("Form validation failed.");
return;
}
try {
// Configure the submission URL
const submitURL =
options.submitURL || `https://formsubmit.co/ajax/${options.key}`;
// Perform the fetch request
const response = await fetch(submitURL, {
method: "POST",
headers: {
"Content-Type": "application/json",
Accept: "application/json",
},
body: JSON.stringify(options.data || {}),
});
// Handle the response
if (response.ok) {
console.log("Form submitted successfully");
if (options.onSuccess) {
options.onSuccess(response);
}
} else {
console.error("Form submission failed");
if (options.onError) {
options.onError(response);
}
}
} catch (error) {
console.error("An error occurred:", error);
if (options.onError) {
options.onError(error);
}
}
});
}