document.addEventListener('DOMContentLoaded', function () {
const contactForm = document.getElementById('contactForm');
if (contactForm) {
contactForm.addEventListener('submit', function (e) {
e.preventDefault();
const form = e.target;
const formData = new FormData(form);
const alertContainer = document.getElementById('form-alerts');
alertContainer.innerHTML = '';
fetch('contact.php', {
method: 'POST',
body: formData
})
.then(response => response.json())
.then(data => {
if (data.success) {
showAlert('success', 'Message sent successfully! We will get back to you shortly.');
form.reset();
} else {
showAlert('danger', 'An error occurred: ' + (data.error || 'Please try again.'));
}
})
.catch(error => {
showAlert('danger', 'A network error occurred. Please try again.');
console.error('Error:', error);
});
});
}
function showAlert(type, message) {
const alertContainer = document.getElementById('form-alerts');
const wrapper = document.createElement('div');
wrapper.innerHTML = [
`
'
].join('');
alertContainer.append(wrapper);
}
// --- Search Functionality ---
const searchForm = document.getElementById('searchForm');
if (searchForm) {
const searchInput = document.getElementById('searchInput');
const searchButton = document.getElementById('searchButton');
const searchResultsSection = document.getElementById('searchResults');
const resultsContainer = document.getElementById('resultsContainer');
const noResults = document.getElementById('noResults');
searchForm.addEventListener('submit', function(e) {
e.preventDefault();
const query = searchInput.value.trim();
if (query === '') {
return;
}
// Show loading state
searchButton.disabled = true;
searchButton.innerHTML = ' Searching...';
resultsContainer.innerHTML = '';
noResults.style.display = 'none';
searchResultsSection.style.display = 'block';
fetch(`search.php?q=${encodeURIComponent(query)}`)
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
})
.then(data => {
if (data.length > 0) {
displayResults(data);
} else {
noResults.style.display = 'block';
}
})
.catch(error => {
console.error('Search error:', error);
resultsContainer.innerHTML = 'An error occurred while searching. Please try again.
';
})
.finally(() => {
// Restore button state
searchButton.disabled = false;
searchButton.innerHTML = 'Search';
});
});
function displayResults(products) {
products.forEach(product => {
const pricesHtml = product.prices.map(p => `
${p.retailer}
R ${parseFloat(p.price).toFixed(2)}
`).join('');
const productCard = `
`;
resultsContainer.innerHTML += productCard;
});
}
}
});