$(document).ready(function() { function getCookie(name) { let cookieValue = null; if (document.cookie && document.cookie !== '') { const cookies = document.cookie.split(';'); for (let i = 0; i < cookies.length; i++) { const cookie = cookies[i].trim(); if (cookie.substring(0, name.length + 1) === (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } const csrftoken = getCookie('csrftoken'); $('#contact-form').on('submit', function(e) { e.preventDefault(); // Останавливаем стандартную отправку формы $.ajax({ type: 'POST', url: "/contact/", // URL, который будет обрабатывать запрос data: { 'name': $('input[name=name]').val(), 'email': $('input[name=email]').val(), 'phone': $('input[name=phone]').val(), 'message': $('textarea[name=message]').val(), 'csrfmiddlewaretoken': csrftoken // Передаем CSRF-токен }, success: function(response) { showSuccessMessage(); // Показываем сообщение об успехе через SweetAlert }, error: function(response) { alert('An error occurred. Please try again.'); } }); }); function showSuccessMessage() { Swal.fire({ icon: 'success', title: 'Успех!', text: 'Ваше сообщение было отправлено успешно.', showConfirmButton: false, timer: 3000 // Модальное окно будет отображаться 3 секунды }); } }); document.addEventListener('DOMContentLoaded', function() { const form = document.getElementById('review-form'); form.addEventListener('submit', function(e) { e.preventDefault(); // Останавливаем стандартную отправку формы const formData = new FormData(form); const xhr = new XMLHttpRequest(); xhr.open('POST', form.action, true); xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest'); xhr.onload = function() { if (xhr.status === 200) { const response = JSON.parse(xhr.responseText); if (response.status === 'success') { const reviewSection = document.getElementById('reviews-section'); const newReview = document.createElement('div'); newReview.classList.add('mt-box'); newReview.innerHTML = `
${response.review.name}

${response.review.comment}

`; reviewSection.prepend(newReview); form.reset(); // Сбрасываем форму } } }; xhr.send(formData); }); }); document.addEventListener('DOMContentLoaded', function() { const stars = document.querySelectorAll('.rating-stars .star'); stars.forEach(star => { star.addEventListener('click', function() { const rating = this.previousElementSibling.value; updateStars(rating); }); star.addEventListener('mouseover', function() { const rating = this.previousElementSibling.value; updateStars(rating); }); }); function updateStars(rating) { stars.forEach(star => { const starValue = star.previousElementSibling.value; if (starValue <= rating) { star.style.color = 'black'; } else { star.style.color = 'transparent'; } }); } }); var csrfToken = '{{ csrf_token }}'; // Получение CSRF-токена для использования в AJAX-запросах function decreaseQuantity(button, productId) { var input = button.nextElementSibling; var currentValue = parseInt(input.value); if (currentValue > 1) { input.value = currentValue - 1; updateQuantity(parseInt(productId), 'decrease'); // Передаем productId как число } } function increaseQuantity(button, productId) { var input = button.previousElementSibling; var currentValue = parseInt(input.value); input.value = currentValue + 1; updateQuantity(parseInt(productId), 'increase'); // Передаем productId как число } function updateQuantity(productId, action) { const data = { 'product_id': productId, 'action': action }; console.log("Отправляемые данные:", data); $.ajax({ url: '{% url "update_cart_item" %}', type: 'POST', headers: { 'X-CSRFToken': csrfToken, }, data: JSON.stringify(data), contentType: 'application/json', success: function(data) { if (data.success) { // Перезагружаем страницу после успешного обновления location.reload(); } else { console.error('Error updating cart:', data.error); } }, error: function(xhr, status, error) { console.error('AJAX error:', status, error); } }); } document.addEventListener('DOMContentLoaded', function() { document.querySelectorAll('.remove-from-cart').forEach(function(button) { button.addEventListener('click', function(event) { event.preventDefault(); var productId = this.getAttribute('data-product-id'); if (!productId) return; fetch('/carts/remove_item/', { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-CSRFToken': getCookie('csrftoken') // Убедитесь, что CSRF токен правильно передается }, body: JSON.stringify({ 'productId': productId }) }) .then(response => response.json()) .then(data => { if (data.success) { // Обновите отображение корзины, например, пересчитайте общую сумму document.getElementById('total-price').innerText = data.new_total_price; this.closest('li').remove(); // Удаление элемента из DOM } else { console.error('Ошибка: ' + data.error); } }) .catch(error => console.error('Ошибка:', error)); }); }); }); // Функция для получения CSRF токена из кукисов function getCookie(name) { let cookieValue = null; if (document.cookie && document.cookie !== '') { const cookies = document.cookie.split(';'); for (let i = 0; i < cookies.length; i++) { const cookie = cookies[i].trim(); if (cookie.substring(0, name.length + 1) === (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } document.addEventListener('DOMContentLoaded', function () { var searchInput = document.querySelector('input[type="text"]'); var searchResults = document.getElementById('search-results'); function performSearch() { var query = searchInput.value.trim(); // Убираем пробелы в начале и конце if (query.length > 2) { fetch('/product/ajax/search/?query=' + encodeURIComponent(query)) .then(response => { if (!response.ok) { throw new Error('Network response was not ok'); } return response.json(); }) .then(data => { searchResults.innerHTML = ''; // Очищаем предыдущие результаты let foundSomething = false; if (data.categories && data.categories.length > 0) { foundSomething = true; data.categories.forEach(category => { var categoryDiv = document.createElement('div'); var categoryLink = document.createElement('a'); categoryLink.className = 'search-result-category'; categoryLink.href = '/product/?category=' + category.id; categoryLink.textContent = 'Категории: ' + category.title; categoryDiv.appendChild(categoryLink); searchResults.appendChild(categoryDiv); }); } if (data.products && data.products.length > 0) { foundSomething = true; data.products.forEach(product => { var productDiv = document.createElement('div'); var productLink = document.createElement('a'); productLink.className = 'search-result-product'; productLink.href = '/product/' + product.id; productLink.textContent = product.title + ' - ' + product.price; productDiv.appendChild(productLink); searchResults.appendChild(productDiv); }); } if (!foundSomething) { var noResultsDiv = document.createElement('div'); noResultsDiv.className = 'search-no-results'; noResultsDiv.textContent = 'Ничего не найдено.'; searchResults.appendChild(noResultsDiv); } }) .catch(error => { console.error('Error fetching search results:', error); searchResults.innerHTML = 'Произошла ошибка при получении результатов поиска. Пожалуйста, повторите попытку позже.'; }); } else { searchResults.innerHTML = ''; } } searchInput.addEventListener('input', performSearch); });