«Поддельное предупреждение «Пожалуйста, выберите вариант» на кнопке «Добавить в корзину» при выборе варианта продукта WoPhp

Кемеровские программисты php общаются здесь
Ответить Пред. темаСлед. тема
Anonymous
 «Поддельное предупреждение «Пожалуйста, выберите вариант» на кнопке «Добавить в корзину» при выборе варианта продукта Wo

Сообщение Anonymous »

Я работаю над пользовательской страницей продукта WooCommerce, где пользователь может выбирать варианты продукта (например, размер, цвет и т. д.), а затем добавлять продукт в корзину. Все работает правильно, включая выбор варианта и динамическое обновление цены на основе выбранного варианта.
Однако я столкнулся с проблемой. Когда пользователь выбирает вариант и нажимает кнопку «Добавить в корзину», появляется ложное предупреждение с надписью «Пожалуйста, выберите вариант», даже если действительный вариант уже выбран. После закрытия этого поддельного оповещения товар успешно добавляется в корзину и появляется сообщение об успехе.
Я хочу, чтобы это поддельное оповещение не отображалось при успешном добавлении товара в корзину. . Как я могу изменить обработку событий, чтобы отображалось только оповещение об успехе, а не ложное оповещение?
Любая помощь или предложения приветствуются!
global $product;

// Get the product's default price HTML

$default_price_html = $product->get_price_html();

// Get available variations

$available_variations = $product->get_available_variations();

$product_id = $product->get_id();

echo '';

echo '
Price: ' .  $default_price_html . '
';

echo '';

echo '';

$attributes = $product->get_variation_attributes();

foreach ($attributes as $attribute_name => $options) {

    echo '';

    foreach ($options as $index => $option) {

        $input_id = 'attribute_' . sanitize_title($attribute_name) . '_' . $product_id . '_' . $index;

        echo '';

        echo '' . esc_html($option) . '';

    }

    echo '';

}

echo '';

echo '';

echo 'Add to Cart';

echo '';

echo '

document.addEventListener("DOMContentLoaded", function () {

    var productID = "' . $product_id . '";

    var variationOptions = document.querySelectorAll(".variation-option[data-product_id=\'" + productID + "\']");

    var priceElement = document.getElementById("product-price-" + productID);

    var addToCartButton = document.getElementById("add-to-cart-button-" + productID);

    var selectedVariationId = null;

    var availableVariations = ' . json_encode($available_variations, JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT) . ';

    var defaultPriceHtml = ' . json_encode($default_price_html) . ';

    // Function to update the price display

    function updatePrice(priceHtml) {

        priceElement.innerHTML = "Price: " + priceHtml;

    }

    // Function to find and set the matching variation

    function findMatchingVariation(selectedAttributes) {

        return availableVariations.find(function (variation) {

            return Object.keys(selectedAttributes).every(function (key) {

                return variation.attributes[key] === selectedAttributes[key];

            });

        });

    }

    // Function to gather selected attributes

    function getSelectedAttributes() {

        var selectedAttributes = {};

        variationOptions.forEach(function (opt) {

            if (opt.checked) {

                var attrName = "attribute_" + opt.getAttribute("data-attribute_name");

                selectedAttributes[attrName] = opt.value;

            }

        });

        return selectedAttributes;

    }

    // Event listener for option changes

    variationOptions.forEach(function (option) {

        option.addEventListener("change", function () {

            var selectedAttributes = getSelectedAttributes();

            // Find matching variation

            var matchingVariation = findMatchingVariation(selectedAttributes);

            // Update the price and enable the Add to Cart button if a matching variation is found

            if (matchingVariation) {

                var priceHtml = "$" + matchingVariation.display_price.toFixed(2) + "";

                updatePrice(priceHtml);

                selectedVariationId = matchingVariation.variation_id;

                addToCartButton.disabled = false; // Enable the Add to Cart button

            } else {

                updatePrice(defaultPriceHtml);

                selectedVariationId = null;

                addToCartButton.disabled = true; // Disable the Add to Cart button

            }

        });

    });

    // Add to Cart button click event

    addToCartButton.addEventListener("click", function (event) {

        // Before proceeding, check if any variation is selected and valid

        if (!selectedVariationId) {

            // Stop the function from proceeding and show the appropriate alert

            event.preventDefault();

            alert("Please select a variation before adding to cart.");

            return;

        }

        // If variation is selected, proceed with the add-to-cart functionality

        var formData = new FormData();

        formData.append("action", "woocommerce_add_to_cart");

        formData.append("product_id", selectedVariationId); // Use the selected variation ID

        formData.append("variation_id", selectedVariationId);

        formData.append("quantity", 1);

        // Include selected attributes in the form data

        var selectedAttributes = getSelectedAttributes();

        for (var key in selectedAttributes) {

            if (selectedAttributes.hasOwnProperty(key)) {

                formData.append(key, selectedAttributes[key]);

            }

        }

        fetch("' . admin_url('admin-ajax.php') . '", {

            method: "POST",

            body: formData,

            credentials: "same-origin"

        })

        .then(function (response) {

            return response.json();

        })

        .then(function (data) {

            if (data.error) {

                alert("Error adding to cart: " + data.error);

            } else {

                alert("Product added to cart successfully!");

                // Optionally, update the cart count or show a success message

                var cartCountElement = document.querySelector(".cart-count");

                if (cartCountElement) {

                    cartCountElement.textContent = data.cart_count;

                }

            }

        })

        .catch(function (error) {

            alert("There was an error processing your request. Please try again.");

        });

    });

});

'; ```


Подробнее здесь: https://stackoverflow.com/questions/791 ... mmerce-pro
Реклама
Ответить Пред. темаСлед. тема

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

  • Похожие темы
    Ответы
    Просмотры
    Последнее сообщение

Вернуться в «Php»