forked from ag_kommunikation/webseite
79 lines
2.9 KiB
JavaScript
79 lines
2.9 KiB
JavaScript
const contactFormAjaxUrl = '/php/contact_form.php';
|
|
const contact_form = document.getElementsByClassName('content__contact_form')[0];
|
|
const subject = document.getElementsByClassName('contact_form__subject')[0];
|
|
const message = document.getElementsByClassName('contact_form__message')[0];
|
|
const name = document.getElementsByClassName('contact_form__name')[0];
|
|
const email = document.getElementsByClassName('contact_form__email')[0];
|
|
const captcha = document.getElementsByClassName('contact_form__captcha')[0];
|
|
const now = (new Date().getTime()/1000).toFixed();
|
|
const feedback = document.getElementsByClassName('contact_form__feedback')[0];
|
|
|
|
window.addEventListener('DOMContentLoaded', function(event) {
|
|
let formData = new FormData();
|
|
formData.append('action', 'start_session');
|
|
fetch(contactFormAjaxUrl, {
|
|
method: 'POST',
|
|
mode: 'same-origin',
|
|
body: formData,
|
|
})
|
|
.then(response => response.json())
|
|
.then(json => {
|
|
console.log(json);
|
|
})
|
|
});
|
|
|
|
contact_form.addEventListener('submit', function(event) {
|
|
event.preventDefault();
|
|
let formData = new FormData();
|
|
formData.append('action', 'handle_form');
|
|
formData.append('subject', subject.value);
|
|
formData.append('message', message.value);
|
|
formData.append('name', name.value);
|
|
formData.append('email', email.value);
|
|
|
|
// If some bot entered some value, return.
|
|
if (typeof captcha.value == 'undefined') {
|
|
formData.append('captcha', 'Nudelsuppe');
|
|
} else {
|
|
console.log('bot detected');
|
|
return;
|
|
}
|
|
|
|
fetch(contactFormAjaxUrl, {
|
|
method: 'POST',
|
|
mode: 'same-origin',
|
|
body: formData,
|
|
})
|
|
.then(response => response.json())
|
|
.then(json => {
|
|
console.log(json);
|
|
if (json.errors) {
|
|
feedback.classList.remove('--success');
|
|
feedback.classList.add('--error');
|
|
// Über errors iterieren und diese ausgeben (evtl. nur ersten Fehler ausgeben?)
|
|
let error_message = '';
|
|
json.errors.forEach(function(error){
|
|
/**
|
|
* Nur Zeilenumbrüche wenn mehrer Fehlermeldungen existieren,
|
|
* aber bei der letzten nicht.
|
|
*/
|
|
if (json.errors.length > 1) {
|
|
if (error == json.errors[json.errors.length - 1]) {
|
|
error_message = error_message + error;
|
|
} else {
|
|
error_message = error_message + error + '<br>';
|
|
}
|
|
} else {
|
|
error_message = error_message + error;
|
|
}
|
|
})
|
|
feedback.innerHTML = error_message;
|
|
} else if (json.status == 'ok') {
|
|
feedback.classList.remove('--error');
|
|
feedback.classList.add('--success');
|
|
feedback.textContent = "Ihre Nachricht wurde erfolgreich ans Office geschickt.";
|
|
}
|
|
})
|
|
.catch(error => console.log(error));
|
|
}, false);
|