| 1 |
(function () { |
| 2 |
'use strict'; |
| 3 |
|
| 4 |
document.querySelectorAll('.bkbg-cs-wrapper form.bkbg-cs-form').forEach(function (form) { |
| 5 |
var msgEl = form.querySelector('.bkbg-cs-form-msg'); |
| 6 |
var submitBtn = form.querySelector('.bkbg-cs-submit'); |
| 7 |
var recipient = form.getAttribute('data-recipient') || ''; |
| 8 |
var successMsg= form.getAttribute('data-success') || 'Thank you! Your message has been sent.'; |
| 9 |
|
| 10 |
form.addEventListener('submit', function (e) { |
| 11 |
e.preventDefault(); |
| 12 |
|
| 13 |
var data = new FormData(form); |
| 14 |
data.append('action', 'bkbg_contact_form'); |
| 15 |
data.append('recipient', recipient); |
| 16 |
data.append('nonce', (window.bkbgContactData && window.bkbgContactData.nonce) || ''); |
| 17 |
|
| 18 |
if (submitBtn) { submitBtn.disabled = true; submitBtn.style.opacity = '0.6'; } |
| 19 |
if (msgEl) { msgEl.textContent = ''; msgEl.className = 'bkbg-cs-form-msg'; } |
| 20 |
|
| 21 |
var ajaxUrl = (window.bkbgContactData && window.bkbgContactData.ajaxUrl) |
| 22 |
|| (window.wpAjaxUrl) |
| 23 |
|| '/wp-admin/admin-ajax.php'; |
| 24 |
|
| 25 |
fetch(ajaxUrl, { method: 'POST', body: data }) |
| 26 |
.then(function (res) { return res.json(); }) |
| 27 |
.then(function (json) { |
| 28 |
if (json && json.success) { |
| 29 |
if (msgEl) { msgEl.textContent = successMsg; msgEl.classList.add('is-success'); } |
| 30 |
form.reset(); |
| 31 |
} else { |
| 32 |
var err = (json && json.data && json.data.message) || 'Something went wrong. Please try again.'; |
| 33 |
if (msgEl) { msgEl.textContent = err; msgEl.classList.add('is-error'); } |
| 34 |
} |
| 35 |
}) |
| 36 |
.catch(function () { |
| 37 |
if (msgEl) { msgEl.textContent = 'Network error. Please try again.'; msgEl.classList.add('is-error'); } |
| 38 |
}) |
| 39 |
.finally(function () { |
| 40 |
if (submitBtn) { submitBtn.disabled = false; submitBtn.style.opacity = ''; } |
| 41 |
}); |
| 42 |
}); |
| 43 |
}); |
| 44 |
})(); |
| 45 |
|