-
Notifications
You must be signed in to change notification settings - Fork 0
/
form.js
97 lines (92 loc) · 2.66 KB
/
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
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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
/**
* @classdesc Represents a FabrForm component.
* @extends FabrCoreComponent
*/
fbr.FabrForm = class extends fbr.FabrCoreComponent {
constructor() {
super();
this.componentName = "FabrForm";
this.componentStyleClass = "fabr-form";
this.selector = "[fabr-form]";
this.eventMap = {
submit: "onSubmit",
};
this.toastHelper = new fbr.FabrHelperToast();
this.toastHelper.init(this);
}
/**
* Handle the form submission event.
* @param {Event} event - The event object.
*/
onSubmit(event) {
event.preventDefault();
const formData = new FormData(event.target);
const formAction = event.target.action;
if (event.target.hasAttribute("fabr-form-response")) {
const responseUrl = event.target.getAttribute("fabr-form-response");
this.#getResponse(responseUrl)
.then((data) => {
if (data.status === 200) {
if (data.redirect) {
window.location.href = data.redirect;
} else {
this.toastHelper.showToast(data.message, "success", 3000, true);
}
} else {
this.toastHelper.showToast(data.message, "error", 0, true);
}
})
.catch((error) => console.error("Error:", error));
return;
}
this.#submitForm(formAction, formData)
.then((data) => {
if (data.status === 200) {
if (data.redirect) {
window.location.href = data.redirect;
} else {
this.toastHelper.showToast(data.message, "success", 3000, true);
}
} else {
this.toastHelper.showToast(data.message, "error", 0, true);
}
})
.catch((error) => console.error("Error:", error));
}
/**
* Get the response from the server.
* @param {string} responseUrl - The URL to fetch the response from.
* @returns {Promise} - The response from the server.
* @private
*/
#getResponse(responseUrl) {
return fetch(responseUrl)
.then((response) => response.json())
.then((data) => {
return data;
})
.catch((error) => {
console.error("Error:", error);
});
}
/**
* Submit the form to the server.
* @param {string} formAction - The URL to submit the form to.
* @param {FormData} formData - The form data to submit.
* @returns {Promise} - The response from the server.
* @private
*/
#submitForm(formAction, formData) {
return fetch(formAction, {
method: "POST",
body: formData,
})
.then((response) => response.json())
.then((data) => {
return data;
})
.catch((error) => {
console.error("Error:", error);
});
}
};