document.addEventListener('DOMContentLoaded', () => { const addListingForm = document.getElementById('add-listing-form'); const listingsContainer = document.getElementById('listings-container'); const formMessage = document.getElementById('form-message'); const API_URL = 'api.php'; // --- Fetch and Display Listings --- async function fetchListings() { try { const response = await fetch(`${API_URL}?action=list`); if (!response.ok) { throw new Error(`HTTP error! status: ${response.status}`); } const listings = await response.json(); displayListings(listings); } catch (error) { console.error("Error fetching listings:", error); listingsContainer.innerHTML = '

Error loading listings. Please try again later.

'; } } function displayListings(listings) { listingsContainer.innerHTML = ''; // Clear current listings or loading message if (listings.length === 0) { listingsContainer.innerHTML = '

No listings available at the moment.

'; return; } listings.forEach(listing => { const card = document.createElement('div'); card.classList.add('listing-card'); let imageHtml = ''; if (listing.image_url) { imageHtml = `${listing.title}`; } card.innerHTML = ` ${imageHtml}

${listing.title}

${listing.description}

Location: ${listing.location}

Price: $${parseFloat(listing.price).toFixed(2)}

`; listingsContainer.appendChild(card); }); } // --- Add New Listing --- addListingForm.addEventListener('submit', async (event) => { event.preventDefault(); formMessage.textContent = ''; // Clear previous messages const formData = new FormData(addListingForm); const data = {}; formData.forEach((value, key) => data[key] = value); // Basic client-side validation (can be more extensive) if (!data.title || !data.description || !data.price || !data.location) { formMessage.textContent = 'Please fill in all required fields.'; formMessage.className = 'error'; return; } try { const response = await fetch(`${API_URL}?action=add`, { method: 'POST', body: formData // FormData sends as 'multipart/form-data' or 'x-www-form-urlencoded' // PHP's $_POST will pick it up. }); const result = await response.json(); if (result.success) { formMessage.textContent = 'Listing added successfully!'; formMessage.className = 'success'; addListingForm.reset(); // Clear the form fetchListings(); // Refresh the listings } else { formMessage.textContent = `Error: ${result.message || 'Could not add listing.'}`; formMessage.className = 'error'; } } catch (error) { console.error("Error adding listing:", error); formMessage.textContent = 'An unexpected error occurred. Please try again.'; formMessage.className = 'error'; } }); // --- Initial Load --- fetchListings(); });