forked from raspgot/Contact-Form-PHP
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAjaxForm.js
83 lines (74 loc) · 3 KB
/
AjaxForm.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
/**
* .checkValidity | https://getbootstrap.com/docs/5.3/forms/validation
* FormData | https://developer.mozilla.org/en-US/docs/Web/API/FormData
* fetch | https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API
* reCaptcha v3 | https://developers.google.com/recaptcha/docs/v3
*
* @author Raspgot
*/
const reCAPTCHA_site_key = 'GOOGLE_PUBLIC_KEY'; // GOOGLE public key
onload = (event) => {
'use strict'
// Execute grecaptcha initialization
checkRecaptcha(event);
let forms = document.querySelectorAll('.needs-validation');
let spinner = document.getElementById('loading-spinner');
let button = document.querySelector('button[type="submit"]');
Array.prototype.filter.call(forms, function (form) {
form.addEventListener('submit', function (event) {
if (form.checkValidity() === false) {
event.preventDefault();
event.stopPropagation();
}
form.classList.add('was-validated');
if (form.checkValidity() === true) {
event.preventDefault();
form.classList.remove('was-validated');
spinner.classList.remove('d-none');
button.disabled = true;
let data = new FormData(form);
let alertClass = 'alert-danger';
fetch('AjaxForm.php', {
method: 'post',
body: data
}).then((data) => {
return data.text();
}).then((txt) => {
txt = JSON.parse(txt);
if (txt.error === false) {
alertClass = 'alert-success';
}
let alertBox = '<div class="alert ' + alertClass + '">' + txt.message + '</div>';
if (alertClass && txt) {
form.querySelector('#alert-statut').insertAdjacentHTML('beforeend', alertBox);
form.reset();
checkRecaptcha(event);
}
spinner.classList.add('d-none');
button.disabled = false;
setTimeout(function () {
form.querySelector('#alert-statut').innerHTML = '';
}, 5000);
}).catch((err) => {
console.log('Error encountered: ' + err);
spinner.classList.add('d-none');
button.disabled = false;
});
}
}, false);
});
};
/**
* @link https://developers.google.com/recaptcha/docs/v3#programmatically_invoke_the_challenge
*/
const checkRecaptcha = (event) => {
event.preventDefault();
grecaptcha.ready(function () {
grecaptcha.execute(reCAPTCHA_site_key, {
action: 'submit'
}).then(function (token) {
// Input with recaptcha-token name take the recaptcha token value
document.getElementsByName('recaptcha-token')[0].value = token;
});
});
};