forked from NoCodeQuest/Send-Form-Submission-To-Webflow-CMS
-
Notifications
You must be signed in to change notification settings - Fork 0
/
submitForm.js
92 lines (73 loc) · 2.16 KB
/
submitForm.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
var Webflow = Webflow || [];
Webflow.push(function() {
// display error message
function displayError(message) {
hideLoading();
failureMessage.innerText = message;
failureMessage.style.display = 'block';
}
// hiding the loading indicator
function hideLoading() {
showForm();
successMessage.style.display = 'none';
}
// hide the form
function hideForm() {
form.style.display = 'none';
}
// show the loading indicator
function showLoading() {
hideForm();
successMessage.style.display = 'block';
}
// show the form
function showForm() {
form.style.display = 'block';
}
// listen for xhr events
function addListeners(xhr) {
xhr.addEventListener('loadstart', showLoading);
}
// add xhr settings
function addSettings(xhr) {
xhr.timeout = requestTimeout;
}
// triggered form submit
function triggerSubmit(event) {
// prevent default behavior form submit behavior
event.preventDefault();
// setup + send xhr request
let formData = new FormData(event.target);
let xhr = new XMLHttpRequest();
xhr.open('POST', event.srcElement.action);
addListeners(xhr);
addSettings(xhr);
xhr.send(formData);
// capture xhr response
xhr.onload = function() {
if (xhr.status === 302) {
let data = JSON.parse(xhr.responseText);
window.location.assign(event.srcElement.dataset.redirect + data.slug);
} else {
displayError(errorMessage);
}
}
// capture xhr request timeout
xhr.ontimeout = function() {
displayError(errorMessageTimedOut);
}
}
// replace with your form ID
const form = document.getElementById('profile-form');
// set the Webflow Error Message Div Block ID to 'error-message'
let failureMessage = document.getElementById('error-message');
// set the Webflow Success Message Div Block ID to 'success-message'
let successMessage = document.getElementById('success-message');
// set request timeout in milliseconds (1000ms = 1second)
let requestTimeout = 10000;
// error messages
let errorMessageTimedOut = 'Oops! Seems this timed out. Please try again.';
let errorMessage = 'Oops! Something went wrong. Please try again.';
// capture form submit
form.addEventListener('submit', triggerSubmit);
});