/
Evil331
/
Apteka
Обзор
Документация
Войти
/
Evil331
/
Apteka
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
Аналитика
Безопасность
main
script.js
378 строк
16 KB
Evil6766
Add files via upload
31 май 2025, 17:06
Не верифицирован
31 май 2025, 17:06
667fe25
Код
Авторство
О чём код?
// Инициализация при загрузке страницы document.addEventListener('DOMContentLoaded', function() { console.log('Страница загружена, инициализация событий...'); updateCartCount(); bindEventListeners(); bindSearchListeners(); bindAddToCartButtons(); applyFilters(); updateCartDisplayIfNeeded(); handleCheckoutForm(); }); // Привязка обработчиков событий к элементам корзины function bindEventListeners() { // Удаляем старые обработчики, чтобы избежать дублирования const increaseButtons = document.querySelectorAll('.increase-quantity'); const decreaseButtons = document.querySelectorAll('.decrease-quantity'); const removeButtons = document.querySelectorAll('.remove-item'); const quantityInputs = document.querySelectorAll('.quantity-input'); increaseButtons.forEach(button => { button.removeEventListener('click', handleIncreaseQuantity); button.addEventListener('click', handleIncreaseQuantity); }); decreaseButtons.forEach(button => { button.removeEventListener('click', handleDecreaseQuantity); button.addEventListener('click', handleDecreaseQuantity); }); removeButtons.forEach(button => { button.removeEventListener('click', handleRemoveItem); button.addEventListener('click', handleRemoveItem); }); quantityInputs.forEach(input => { input.removeEventListener('change', handleQuantityInputChange); input.addEventListener('change', handleQuantityInputChange); }); } // Привязка обработчиков для поиска function bindSearchListeners() { const searchInput = document.getElementById('searchInput'); const searchButton = document.getElementById('searchButton'); if (searchInput && searchButton) { console.log('Элементы поиска найдены, добавляем обработчики событий.'); searchInput.addEventListener('keypress', function(e) { if (e.key === 'Enter') { console.log('Поиск по Enter'); handleSearch(); } }); searchButton.addEventListener('click', function(e) { console.log('Кнопка поиска нажата'); handleSearch(); }); } else { console.warn('Элементы поиска не найдены: input=', !!searchInput, 'button=', !!searchButton); } } // Привязка событий к кнопкам "Добавить в корзину" function bindAddToCartButtons() { const addToCartButtons = document.querySelectorAll('.add-to-cart'); if (addToCartButtons.length > 0) { addToCartButtons.forEach(button => { button.addEventListener('click', function () { const productId = this.getAttribute('data-id'); const productName = this.getAttribute('data-name'); const price = this.getAttribute('data-price'); addToCart(productId, productName, price); }); }); } } bindCartEventListeners(); }); // Обработчик добавления товара в корзину function handleAddToCart(event) { const button = event.target; const productId = button.getAttribute('data-id'); const productName = button.getAttribute('data-name'); const price = button.getAttribute('data-price'); if (productId && productName && price) { addToCart(productId, productName, price); } else { console.error('Недостаточно данных для добавления в корзину'); alert('Ошибка: данные о товаре отсутствуют.'); } } // Обработчик увеличения количества function handleIncreaseQuantity(event) { const productId = event.target.getAttribute('data-id'); const quantityInput = document.querySelector(`.quantity-input[data-id="${productId}"]`); let quantity = parseInt(quantityInput.value); quantityInput.value = quantity + 1; updateQuantity(productId, quantity + 1); } // Обработчик уменьшения количества function handleDecreaseQuantity(event) { const productId = event.target.getAttribute('data-id'); const quantityInput = document.querySelector(`.quantity-input[data-id="${productId}"]`); let quantity = parseInt(quantityInput.value); if (quantity > 1) { quantityInput.value = quantity - 1; updateQuantity(productId, quantity - 1); } } // Обработчик изменения значения в input function handleQuantityInputChange(event) { const productId = event.target.getAttribute('data-id'); let quantity = parseInt(event.target.value); if (isNaN(quantity) || quantity < 1) { event.target.value = 1; quantity = 1; } updateQuantity(productId, quantity); } // Обработчик удаления товара function handleRemoveItem(event) { const productId = event.target.getAttribute('data-id'); removeFromCart(productId); } // Обработчик оформления заказа let isCheckoutProcessing = false; // Защита от множественных отправок function handleCheckout() { if (isCheckoutProcessing) return; // Игнорируем, если запрос уже выполняется isCheckoutProcessing = true; const checkoutButton = document.querySelector('#checkout-button'); if (checkoutButton) { checkoutButton.disabled = true; checkoutButton.textContent = 'Обработка...'; } fetch('process_order.php', { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' } }) .then(response => response.json()) .then(data => { if (data.success) { alert('Заказ успешно оформлен!'); updateCartCount(); window.location.href = 'order_confirmation.php'; } else { alert('Ошибка при оформлении заказа: ' + (data.message || 'Неизвестная ошибка')); console.error('Ошибка оформления заказа:', data); } }) .catch(error => { console.error('Ошибка сети:', error); alert('Произошла ошибка. Пожалуйста, попробуйте позже.'); }) .finally(() => { isCheckoutProcessing = false; if (checkoutButton) { checkoutButton.disabled = false; checkoutButton.textContent = 'Оформить заказ'; } }); } // Обработка формы оформления заказа (если используется форма) function handleCheckoutForm() { const checkoutForm = document.getElementById('checkoutForm'); const checkoutButton = document.querySelector('#checkout-button'); if (checkoutForm) { checkoutForm.addEventListener('submit', function(e) { e.preventDefault(); handleCheckout(); }); } else if (checkoutButton) { checkoutButton.removeEventListener('click', handleCheckout); checkoutButton.addEventListener('click', handleCheckout); } } // Обновление количества товара с debounce let debounceTimer = null; function updateQuantity(productId, quantity) { if (debounceTimer) { clearTimeout(debounceTimer); } debounceTimer = setTimeout(() => { fetch('update_cart.php', { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, body: `product_id=${encodeURIComponent(productId)}&quantity=${encodeURIComponent(quantity)}` }) .then(response => response.json()) .then(data => { if (data.success) { updateCartDisplay(); updateCartCount(); } else { alert('Ошибка обновления количества: ' + (data.message || 'Неизвестная ошибка')); console.error('Ошибка обновления:', data); } }) .catch(error => console.error('Ошибка сети:', error)); }, 300); } // Удаление товара из корзины function removeFromCart(productId) { fetch('remove_from_cart.php', { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, body: `product_id=${encodeURIComponent(productId)}` }) .then(response => response.json()) .then(data => { if (data.success) { updateCartDisplay(); updateCartCount(); } else { alert('Ошибка удаления товара: ' + (data.message || 'Неизвестная ошибка')); console.error('Ошибка удаления:', data); } }) .catch(error => console.error('Ошибка сети:', error)); } // Обновление отображения корзины function updateCartDisplay() { fetch('get_cart_items.php') .then(response => response.json()) .then(data => { const cartItemsContainer = document.querySelector('.cart-items'); const cartTotal = document.querySelector('#cart-total'); const mainContainer = document.querySelector('main.container'); if (!cartItemsContainer || !mainContainer) return; // Если контейнеров нет, выходим if (!data.items || data.items.length === 0) { mainContainer.innerHTML = `<h2>Ваша корзина</h2><p class="empty-cart">Корзина пуста. <a href="catalog.php">Перейти в каталог</a></p>`; return; } let total = 0; cartItemsContainer.innerHTML = ''; data.items.forEach(item => { total += item.price * item.quantity; cartItemsContainer.innerHTML += ` <div class="cart-item" data-id="${item.product_id}"> <img src="${item.image_url}" alt="${item.name}" class="cart-item-image"> <div class="cart-item-details"> <h3>${item.name}</h3> <p>Цена: ${item.price.toFixed(2)} RUB</p> <div class="quantity-control"> <button class="decrease-quantity" data-id="${item.product_id}">-</button> <input type="number" value="${item.quantity}" min="1" class="quantity-input" data-id="${item.product_id}"> <button class="increase-quantity" data-id="${item.product_id}">+</button> </div> </div> <div class="cart-item-total"> Итого: ${(item.price * item.quantity).toFixed(2)} RUB </div> <button class="remove-item" data-id="${item.product_id}">Удалить</button> </div> `; }); if (cartTotal) { cartTotal.textContent = total.toFixed(2) + ' RUB'; } bindEventListeners(); // Повторно привязываем обработчики событий }) .catch(error => console.error('Ошибка обновления корзины:', error)); } // Проверка и обновление отображения корзины, если находимся на странице корзины function updateCartDisplayIfNeeded() { const cartItemsContainer = document.querySelector('.cart-items'); if (cartItemsContainer) { updateCartDisplay(); } } // Обновление счетчика корзины function updateCartCount() { fetch('get_cart_count.php') .then(response => response.json()) .then(data => { const cartLink = document.getElementById('cartLink'); if (cartLink) { cartLink.textContent = `Корзина (${data.count || 0})`; } }) .catch(error => console.error('Ошибка обновления счетчика:', error)); } // Добавление товара в корзину function addToCart(productId, productName, price) { fetch('add_to_cart.php', { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, body: `product_id=${encodeURIComponent(productId)}&quantity=1` }) .then(response => response.json()) .then(data => { if (data.success) { alert(`${productName} добавлен в корзину!`); updateCartCount(); } else { alert('Ошибка: ' + (data.message || 'Неизвестная ошибка')); console.error('Ошибка добавления в корзину:', data); } }) .catch(error => { console.error('Ошибка сети:', error); alert('Произошла ошибка. Пожалуйста, попробуйте позже.'); }); } // Обработчик поиска function handleSearch() { const searchInput = document.getElementById('searchInput'); if (!searchInput) { console.error('Ошибка: Поле поиска не найдено на странице.'); return; } const searchQuery = searchInput.value.trim(); let redirectUrl = 'catalog.php'; if (searchQuery) { redirectUrl += `?search=${encodeURIComponent(searchQuery)}`; } console.log('Перенаправление на:', redirectUrl); window.location.href = redirectUrl; } // Применение фильтров на странице catalog.php function applyFilters() { const filterForm = document.getElementById('filterForm'); const applyFiltersButton = document.getElementById('applyFilters'); if (filterForm && applyFiltersButton) { applyFiltersButton.addEventListener('click', function() { const formData = new FormData(filterForm); const params = new URLSearchParams(formData).toString(); fetch(`filter_products.php?${params}`) .then(response => response.json()) .then(data => { const productGrid = document.getElementById('productGrid'); if (productGrid) { productGrid.innerHTML = ''; if (data.length > 0) { data.forEach(product => { const card = document.createElement('div'); card.className = 'product-card'; card.innerHTML = ` <a href="product.php?id=${product.id}" class="product-link"> <img src="${product.image_url}" alt="${product.name}"> <h3>${product.name}</h3> <p>${product.description}</p> <div class="price">${parseFloat(product.price).toFixed(2)} RUB</div> </a> <button class="add-to-cart" data-id="${product.id}" data-name="${product.name}" data-price="${product.price}">В корзину</button> `; productGrid.appendChild(card); }); bindAddToCartButtons(); // Повторно привязываем события к новым кнопкам } else { productGrid.innerHTML = '<p style="text-align: center; color: #777;">Товары не найдены.</p>'; } } }) .catch(error => console.error('Ошибка при применении фильтров:', error)); }); } }