83 lines
2.4 KiB
JavaScript
83 lines
2.4 KiB
JavaScript
// File: public/assets/js/contact-form.js
|
|
// Version: 1.3
|
|
// Purpose: Handles JS-based form submission with feedback and duplicate prevention
|
|
|
|
|
|
document.addEventListener('DOMContentLoaded', function () {
|
|
const params = new URLSearchParams(window.location.search);
|
|
if (params.get('contact_submitted') || params.get('contact_error')) {
|
|
const contactSection = document.getElementById('contact');
|
|
if (contactSection) {
|
|
contactSection.scrollIntoView({ behavior: 'smooth' });
|
|
}
|
|
}
|
|
|
|
const form = document.querySelector('.php-email-form');
|
|
if (!form) return;
|
|
|
|
const submitButton = form.querySelector('button[type="submit"]');
|
|
|
|
const loading = document.createElement('div');
|
|
const errorMsg = document.createElement('div');
|
|
const successMsg = document.createElement('div');
|
|
|
|
loading.className = 'loading mt-3';
|
|
loading.textContent = 'Sending message...';
|
|
errorMsg.className = 'error-message mt-3';
|
|
errorMsg.style.display = 'none';
|
|
successMsg.className = 'sent-message mt-3';
|
|
successMsg.style.display = 'none';
|
|
|
|
form.appendChild(loading);
|
|
form.appendChild(errorMsg);
|
|
form.appendChild(successMsg);
|
|
|
|
loading.style.display = 'none';
|
|
|
|
form.addEventListener('submit', async function (e) {
|
|
e.preventDefault();
|
|
|
|
if (submitButton.disabled) return; // prevent double click
|
|
submitButton.disabled = true;
|
|
|
|
loading.style.display = 'block';
|
|
errorMsg.style.display = 'none';
|
|
successMsg.style.display = 'none';
|
|
|
|
const formData = new FormData(form);
|
|
|
|
try {
|
|
const response = await fetch(form.action, {
|
|
method: 'POST',
|
|
headers: { 'X-Requested-With': 'XMLHttpRequest' },
|
|
body: formData
|
|
});
|
|
|
|
|
|
const result = await response.json();
|
|
loading.style.display = 'none';
|
|
submitButton.disabled = false;
|
|
|
|
if (response.ok && result.success) {
|
|
successMsg.textContent = result.message || 'Your message was sent successfully.';
|
|
successMsg.style.display = 'block';
|
|
form.reset();
|
|
} else {
|
|
throw new Error(result.error || 'Submission failed.');
|
|
}
|
|
} catch (err) {
|
|
loading.style.display = 'none';
|
|
submitButton.disabled = false;
|
|
errorMsg.textContent = err.message || 'An unexpected error occurred.';
|
|
errorMsg.style.display = 'block';
|
|
}
|
|
});
|
|
});
|
|
|
|
window.prefillService = function (serviceName) {
|
|
const subjectField = document.getElementById('subject');
|
|
if (subjectField) {
|
|
subjectField.value = `Inquiry about ${serviceName}`;
|
|
}
|
|
};
|
|
|