From 09bfba2c6c848e95c18763eb08ca74e58af5eef3 Mon Sep 17 00:00:00 2001 From: maksim Date: Wed, 11 Jun 2025 14:38:46 +0300 Subject: [PATCH] =?UTF-8?q?Task:=206705=20|=20=D0=9D=D0=B5=20=D1=80=D0=B0?= =?UTF-8?q?=D0=B1=D0=BE=D1=82=D0=B0=D0=B5=D1=82=20AJAX=20=D0=B4=D0=BE?= =?UTF-8?q?=D0=B1=D0=B0=D0=B2=D0=BB=D0=B5=D0=BD=D0=B8=D0=B5=20=D0=B2=20?= =?UTF-8?q?=D0=BA=D0=BE=D1=80=D0=B7=D0=B8=D0=BD=D1=83=20=D0=BD=D0=B0=20?= =?UTF-8?q?=D0=BF=D0=BE=D0=B4=D1=80=D0=BE=D0=B1=D0=BD=D0=BE=D0=B9=20=D1=81?= =?UTF-8?q?=D1=82=D1=80=D0=B0=D0=BD=D0=B8=D1=86=D0=B5=20=D1=82=D0=BE=D0=B2?= =?UTF-8?q?=D0=B0=D1=80=D0=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../modules/footer/assets/js/footer.js | 48 ------- .../layout/assets/css/gp-style-core.css | 19 +++ .../shop/components/cart/assets/js/cart.js | 126 +++++++++++++----- .../components/cart/component-controller.php | 11 +- .../modules/shop/module-ajax-controller.php | 26 +++- 5 files changed, 149 insertions(+), 81 deletions(-) diff --git a/wp-content/themes/cosmopet/modules/footer/assets/js/footer.js b/wp-content/themes/cosmopet/modules/footer/assets/js/footer.js index a784a0a..16bf619 100644 --- a/wp-content/themes/cosmopet/modules/footer/assets/js/footer.js +++ b/wp-content/themes/cosmopet/modules/footer/assets/js/footer.js @@ -42,54 +42,6 @@ } } }); - // $(document.body).trigger('adding_to_cart', [$thisbutton, data]); - - $.ajax({ - type: 'post', - url: woocommerce_params.ajax_url, - data: data, - beforeSend: function (response) { - $form.find('.detail-block-form__submit, .store-add-to-cart').addClass('loading').attr('disabled', true) - }, - complete: function (response) { - $form.find('.detail-block-form__submit, .store-add-to-cart').removeClass('loading').attr('disabled', false) - }, - success: function (response) { - $('.modal__item.modal__basket').html(response['cart']); - if(response['cart_count'] > 0){ - $('.mini-profile__button--counter').removeClass('disabled').html(response['cart_count']) - } - else{ - $('.mini-profile__button--counter').addClass('disabled').html(response['cart_count']) - } - initCounters(); - let modalF = document.querySelector('.modal'), - aside = document.querySelector('.modal__aside'), - device = window.screen.width; - - if(!$.cookie('gp-cosmopet-cartadd')){ - modalF.classList.add('active'); - $('.modal__basket').addClass('active'); - let thisContentElement = document.querySelector('.modal__basket'); - - let width = thisContentElement.clientWidth; - setTimeout(() => { - if (device <= 720) { - aside.style.width = `${device}px`; - thisContentElement.style.opacity = 1; - thisContentElement.style.filter = 'blur(0px)'; - }else{ - aside.style.width = `${width}px`; - thisContentElement.style.opacity = 1; - thisContentElement.style.filter = 'blur(0px)'; - } - }, 10); - - $.cookie('gp-cosmopet-cartadd', 'true', { expires: 2 }); - } - modalClose('.modal__close'); - }, - }); return false; }); diff --git a/wp-content/themes/cosmopet/modules/layout/assets/css/gp-style-core.css b/wp-content/themes/cosmopet/modules/layout/assets/css/gp-style-core.css index 673e697..6dd7aa8 100644 --- a/wp-content/themes/cosmopet/modules/layout/assets/css/gp-style-core.css +++ b/wp-content/themes/cosmopet/modules/layout/assets/css/gp-style-core.css @@ -2197,4 +2197,23 @@ textarea{ .modal__aside.active { right: 0; +} + +.button.loading::before { + content: ''; + height: 36px; + width: 36px; + position: absolute; + top: 50%; + left: 50%; + transform: translate(-50%, -50%); + background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink' viewBox='0 0 100 100' preserveAspectRatio='xMidYMid' width='200' height='200' style='shape-rendering: auto; display: block; background: transparent;'%3E%3Cg%3E%3Ccircle stroke-dasharray='164.93361431346415 56.97787143782138' r='35' stroke-width='10' stroke='%23000000' fill='none' cy='50' cx='50'%3E%3CanimateTransform keyTimes='0;1' values='0 50 50;360 50 50' dur='1s' repeatCount='indefinite' type='rotate' attributeName='transform'/%3E%3C/circle%3E%3Cg/%3E%3C/g%3E%3C!-- %5Bldio%5D generated by https://loading.io --%3E%3C/svg%3E"); + background-size: contain; + background-repeat: no-repeat; +} + +.button.loading { + font-size: 0; + color: transparent !important; + position: relative; } \ No newline at end of file diff --git a/wp-content/themes/cosmopet/modules/shop/components/cart/assets/js/cart.js b/wp-content/themes/cosmopet/modules/shop/components/cart/assets/js/cart.js index 22571c1..d207893 100644 --- a/wp-content/themes/cosmopet/modules/shop/components/cart/assets/js/cart.js +++ b/wp-content/themes/cosmopet/modules/shop/components/cart/assets/js/cart.js @@ -6,44 +6,43 @@ jQuery(document).ready(function($) { // }); // Обновление количества через input -$(document).on('change', '.counter__input', function () { - const $input = $(this); - const key = $input.data('key'); - const quantity = parseInt($input.val(), 10); + $(document).on('change', '.counter__input', function () { + const $input = $(this); + const key = $input.data('key'); + const quantity = parseInt($input.val(), 10); - if (quantity > 0) { - updateCart(key, quantity, false); + if (quantity > 0) { + updateCart(key, quantity, false); - const $item = $input.closest('.modal-basket-item__control'); - const $priceElement = $item.find('.woocommerce-Price-amount'); - const currentPriceText = $priceElement.text().replace(/[^\d,]/g, '').replace(',', '.'); - const currentTotal = parseFloat(currentPriceText); + const $item = $input.closest('.modal-basket-item__control'); + const $priceElement = $item.find('.woocommerce-Price-amount'); + const currentPriceText = $priceElement.text().replace(/[^\d,]/g, '').replace(',', '.'); + const currentTotal = parseFloat(currentPriceText); - // Защита от деления на 0 - if (!isNaN(currentTotal) && currentTotal > 0) { - const oldQuantity = parseInt($input.prop('defaultValue'), 10); - const unitPrice = currentTotal / oldQuantity; - const newTotal = unitPrice * quantity; + // Защита от деления на 0 + if (!isNaN(currentTotal) && currentTotal > 0) { + const oldQuantity = parseInt($input.prop('defaultValue'), 10); + const unitPrice = currentTotal / oldQuantity; + const newTotal = unitPrice * quantity; - // Получаем текущий символ валюты из разметки - const currencySymbol = $priceElement.find('.woocommerce-Price-currencySymbol').text().trim(); + // Получаем текущий символ валюты из разметки + const currencySymbol = $priceElement.find('.woocommerce-Price-currencySymbol').text().trim(); - // Формируем новую цену с тем же символом - $priceElement.find('bdi').html( - newTotal.toLocaleString('ru-RU', { minimumFractionDigits: 0 }) + - ' ' + currencySymbol + '' - ); + // Формируем новую цену с тем же символом + $priceElement.find('bdi').html( + newTotal.toLocaleString('ru-RU', { minimumFractionDigits: 0 }) + + ' ' + currencySymbol + '' + ); - // Обновить значение по умолчанию (чтобы расчёт unitPrice был корректен в следующий раз) - $input.prop('defaultValue', quantity); - } - } else { - removeItem(key); - } -}); + // Обновить значение по умолчанию (чтобы расчёт unitPrice был корректен в следующий раз) + $input.prop('defaultValue', quantity); + } + } else { + removeItem(key); + } + }); - $(document).on('click', '.modal__basket .counter__button.plus', function(e) { e.preventDefault(); const key = $(this).data('key'); @@ -406,4 +405,69 @@ $(document).on('change', '.counter__input', function () { } } }); -}); \ No newline at end of file + + $('.detail form.cart').on('submit', function(e) { + e.preventDefault(); + + var $form = $(this); + product_id = $form.find('button[name=add-to-cart]').val(), + quantity = $form.find('input.qty').val() || 1; + console.log(product_id); + $.ajax({ + url: wc_add_to_cart_params.ajax_url, + type: 'POST', + data: { + action: 'woocommerce_ajax_add_to_cart', + product_id: product_id, + quantity: quantity, + }, + success: function(response) { + if (response.error && response.product_url) { + window.location = response.product_url; + return; + } + + updateCartFragment(); + openBasketOnFirstAdd(); + }, + error: function(xhr) { + console.log('AJAX Error:', xhr.responseText); + alert('Ошибка добавления товара.'); + } + }); + }); +}); + + +jQuery(function($){ + $('form.cart').on('submit', function(e){ + e.preventDefault(); + + var $form = $(this); + var $button = $form.find('button[type="submit"]'); + + var product_id = $button.val(); + var quantity = $form.find('input.qty').val() || 1; + $.ajax({ + type: 'POST', + url: wc_add_to_cart_params.ajax_url, + data: { + action: 'woocommerce_ajax_add_to_cart', + product_id: product_id, + quantity: quantity, + }, + beforeSend: function() { + $button.addClass('loading'); + }, + success: function(response) { + if (response.error && response.product_url) { + window.location = response.product_url; + return; + } + + $(document.body).trigger('added_to_cart', [response.fragments, response.cart_hash, $button]); + $button.removeClass('loading'); + } + }); + }); +}); diff --git a/wp-content/themes/cosmopet/modules/shop/components/cart/component-controller.php b/wp-content/themes/cosmopet/modules/shop/components/cart/component-controller.php index 2a423c1..4e9f8ad 100644 --- a/wp-content/themes/cosmopet/modules/shop/components/cart/component-controller.php +++ b/wp-content/themes/cosmopet/modules/shop/components/cart/component-controller.php @@ -10,4 +10,13 @@ add_filter('timber/context', function($context) { $context['cart_count'] = WC()->cart->get_cart_contents_count(); return $context; -}); \ No newline at end of file +}); + + +add_action('wp_enqueue_scripts', 'enable_ajax_add_to_cart_single'); +function enable_ajax_add_to_cart_single() { + if (is_product()) { + wp_enqueue_script('wc-add-to-cart-variation'); // для вариативных товаров + wp_enqueue_script('wc-add-to-cart'); // основной скрипт для добавления в корзину + } +} \ No newline at end of file diff --git a/wp-content/themes/cosmopet/modules/shop/module-ajax-controller.php b/wp-content/themes/cosmopet/modules/shop/module-ajax-controller.php index 89f74ec..90a2087 100644 --- a/wp-content/themes/cosmopet/modules/shop/module-ajax-controller.php +++ b/wp-content/themes/cosmopet/modules/shop/module-ajax-controller.php @@ -142,4 +142,28 @@ function handle_remove_cart_item() { } else { wp_send_json_error('Не удалось удалить товар из корзины'); } -} \ No newline at end of file +} + + +add_action('wp_ajax_woocommerce_ajax_add_to_cart', 'woocommerce_ajax_add_to_cart'); +add_action('wp_ajax_nopriv_woocommerce_ajax_add_to_cart', 'woocommerce_ajax_add_to_cart'); + +function woocommerce_ajax_add_to_cart() { + $product_id = apply_filters('woocommerce_add_to_cart_product_id', absint($_POST['product_id'])); + $quantity = empty($_POST['quantity']) ? 1 : wc_stock_amount($_POST['quantity']); + + $passed_validation = apply_filters('woocommerce_add_to_cart_validation', true, $product_id, $quantity); + + if ($passed_validation && WC()->cart->add_to_cart($product_id, $quantity)) { + do_action('woocommerce_ajax_added_to_cart', $product_id); + WC_AJAX::get_refreshed_fragments(); + } else { + $data = array( + 'error' => true, + 'product_url' => apply_filters('woocommerce_cart_redirect_after_error', get_permalink($product_id), $product_id), + ); + echo wp_send_json($data); + } + + wp_die(); +}