63 lines
2.2 KiB
JavaScript
63 lines
2.2 KiB
JavaScript
|
|
/* Kontaktformular: Progressive Enhancement — ohne JS normales POST + Redirect.
|
|||
|
|
Mit JS: fetch-Submit, Status in aria-live-Region, Button-Sperre während des Sendens. */
|
|||
|
|
(function () {
|
|||
|
|
'use strict';
|
|||
|
|
|
|||
|
|
var form = document.querySelector('.form');
|
|||
|
|
if (!form || !window.fetch) {
|
|||
|
|
return;
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
var status = form.querySelector('[data-form-status]');
|
|||
|
|
var button = form.querySelector('button[type="submit"]');
|
|||
|
|
|
|||
|
|
var MESSAGES = {
|
|||
|
|
success: 'Danke für deine Anfrage! Wir melden uns so schnell wie möglich bei dir.',
|
|||
|
|
validation: 'Bitte prüfe deine Eingaben – Pflichtfelder fehlen oder die E-Mail-Adresse ist ungültig.',
|
|||
|
|
mail: 'Deine Nachricht konnte gerade nicht versendet werden. Bitte versuche es später erneut.'
|
|||
|
|
};
|
|||
|
|
|
|||
|
|
function show(type, text) {
|
|||
|
|
var p = document.createElement('p');
|
|||
|
|
p.className = type === 'success' ? 'form__success' : 'form__error';
|
|||
|
|
p.textContent = text;
|
|||
|
|
status.replaceChildren(p);
|
|||
|
|
status.scrollIntoView({ block: 'nearest', behavior: 'smooth' });
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
form.addEventListener('submit', function (event) {
|
|||
|
|
// Native Validierung zuerst (novalidate ist gesetzt, daher manuell).
|
|||
|
|
if (!form.checkValidity()) {
|
|||
|
|
event.preventDefault();
|
|||
|
|
form.reportValidity();
|
|||
|
|
return;
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
event.preventDefault();
|
|||
|
|
button.disabled = true;
|
|||
|
|
button.textContent = 'Wird gesendet …';
|
|||
|
|
|
|||
|
|
fetch(form.action, {
|
|||
|
|
method: 'POST',
|
|||
|
|
body: new FormData(form),
|
|||
|
|
headers: { Accept: 'application/json' }
|
|||
|
|
})
|
|||
|
|
.then(function (response) { return response.json(); })
|
|||
|
|
.then(function (data) {
|
|||
|
|
if (data.ok) {
|
|||
|
|
show('success', MESSAGES.success);
|
|||
|
|
form.reset();
|
|||
|
|
} else {
|
|||
|
|
show('error', MESSAGES[data.error] || MESSAGES.mail);
|
|||
|
|
}
|
|||
|
|
})
|
|||
|
|
.catch(function () {
|
|||
|
|
show('error', MESSAGES.mail);
|
|||
|
|
})
|
|||
|
|
.finally(function () {
|
|||
|
|
button.disabled = false;
|
|||
|
|
button.textContent = 'Nachricht senden';
|
|||
|
|
});
|
|||
|
|
});
|
|||
|
|
})();
|