October 22, 2024
Chicago 12, Melborne City, USA
javascript

Single-Product.php custom variation attribute dropdowns how do I connect ajax add to cart so it shows the attributes as well?


I have a custom dropdown attributes on single-product.php how do I connect the add to cart button together with the dropdown attribute select so the add to car button works based on ajax? Right now only quantity works.

<div class="product-options-grid">
    <?php
    global $product;

    // Check if product is variable or simple
    if ($product->is_type('variable')) {
        $available_variations = $product->get_available_variations();
        $attributes = $product->get_variation_attributes();
        ?>

        <!-- Color Dropdown -->
        <div class="color-dropdown">
            <p>COLOR</p>
            <div class="dropdown-toggle">
                <span class="color-circle"  data-color="<?php echo $attributes['pa_color'][0]; ?>"></span>
                <?php echo $attributes['pa_color'][0]; ?>
                <i class="fa-regular fa-chevron-down"></i>
            </div>
            <div class="dropdown-menu">
                <?php foreach ($attributes['pa_color'] as $color) { ?>
                    <div class="color-option" data-color="<?php echo esc_attr($color); ?>">
                        <span class="color-circle" data-color="<?php echo esc_attr($color); ?>"></span>
                        <?php echo esc_html($color); ?>
                    </div>
                <?php } ?>
            </div>
        </div>

        <!-- Size Dropdown -->
        <div class="size-dropdown">
            <p>SIZE</p>
            <div class="dropdown-toggle">
                <?php echo $attributes['pa_size'][0]; ?>
                <i class="fa-regular fa-chevron-down"></i>
            </div>
            <div class="dropdown-menu">
                <?php foreach ($attributes['pa_size'] as $size) { ?>
                    <div class="size-option" data-size="<?php echo esc_attr($size); ?>">
                        <?php echo esc_html($size); ?>
                    </div>
                <?php } ?>
            </div>
        </div>

        <!-- Quantity Selector -->
        <div class="quantity-selector">
            <p>QUANTITY</p>
            <div class="qty_div">
                <button class="quantity-button minus">-</button>
                <input type="number" id="quantity" name="quantity" value="1" min="1" />
                <button class="quantity-button plus">+</button>
            </div>
        </div>

    <?php
    } else { // Simple Product
    ?>
        <!-- Quantity Selector -->
        <div class="quantity-selector">
            <p>QUANTITY</p>
            <div class="qty_div">
                <button class="quantity-button minus">-</button>
                <input type="number" id="quantity" name="quantity" value="1" min="1" />
                <button class="quantity-button plus">+</button>
            </div>
        </div>
    <?php } ?>
</div>

<div class="shop-buy">
    <button id="add-to-cart" data-product-id="<?php echo $product->get_id(); ?>">
        Add to Cart <i class="fa-light fa-bags-shopping"></i>
    </button>
</div>
document.addEventListener('DOMContentLoaded', function () {
    // Function to toggle dropdown visibility
    document.querySelectorAll('.dropdown-toggle').forEach(toggle => {
        toggle.addEventListener('click', function () {
            const dropdownMenu = this.nextElementSibling;
            dropdownMenu.style.display = dropdownMenu.style.display === 'block' ? 'none' : 'block';
        });
    });

    // Close dropdown if clicking outside
    document.addEventListener('click', function (event) {
        if (!event.target.closest('.color-dropdown') && !event.target.closest('.size-dropdown')) {
            document.querySelectorAll('.dropdown-menu').forEach(menu => {
                menu.style.display = 'none';
            });
        }
    });

    // Event listener for color selection
    document.querySelectorAll('.color-option').forEach(option => {
        option.addEventListener('click', function () {
            const selectedColor = this.getAttribute('data-color');
            const selectedColorName = this.textContent.trim();
            const colorCircle = document.querySelector('.color-dropdown .dropdown-toggle .color-circle');

            colorCircle.style.backgroundColor = selectedColor;
            document.querySelector('.color-dropdown .dropdown-toggle').innerHTML = `<span class="color-circle" style="background-color: ${selectedColor};" data-color="${selectedColor}"></span> ${selectedColorName} <i class="fa-regular fa-chevron-down"></i>`;
            this.parentElement.style.display = 'none';
        });
    });

    // Event listener for size selection
    document.querySelectorAll('.size-option').forEach(option => {
        option.addEventListener('click', function () {
            const selectedSize = this.getAttribute('data-size');
            const selectedSizeName = this.textContent.trim();
            const dropdownToggle = document.querySelector('.size-dropdown .dropdown-toggle');

            dropdownToggle.innerHTML = `${selectedSizeName} <i class="fa-regular fa-chevron-down"></i>`;
            this.parentElement.style.display = 'none';
        });
    });

    // Quantity button functionality
    document.querySelector('.quantity-button.plus').addEventListener('click', function () {
        const quantityInput = document.getElementById('quantity');
        quantityInput.value = parseInt(quantityInput.value) + 1;
    });

    document.querySelector('.quantity-button.minus').addEventListener('click', function () {
        const quantityInput = document.getElementById('quantity');
        if (parseInt(quantityInput.value) > 1) {
            quantityInput.value = parseInt(quantityInput.value) - 1;
        }
    });

   // Add to Cart button functionality with jQuery AJAX
    document.getElementById('add-to-cart').addEventListener('click', function (e) {
        e.preventDefault(); // Prevent default form submission

        const productId = this.getAttribute('data-product-id');
        const selectedColor = document.querySelector('.color-dropdown .dropdown-toggle .color-circle').getAttribute('data-color');
        const selectedSize = document.querySelector('.size-dropdown .dropdown-toggle').textContent.trim();
        const quantity = document.getElementById('quantity').value;

        // Prepare data for AJAX
        const data = {
            product_id: productId,
            quantity: quantity,
            color: selectedColor,
            size: selectedSize,
            action: 'add_to_cart', // This should correspond to your server-side handling
        };

        // Use jQuery AJAX to add to cart
        jQuery.ajax({
            type: "POST",
            url: woocommerce_params.wc_ajax_url.toString().replace("%%endpoint%%", "add_to_cart"),
            data: data,
            beforeSend: function () {
                // Optionally show loading state
                document.getElementById('add-to-cart').classList.add('loading');
            },
            complete: function () {
                // Optionally remove loading state
                document.getElementById('add-to-cart').classList.remove('loading');
            },
            success: function (response) {
                if (response.error && response.product_url) {
                    window.location = response.product_url; // Redirect if there's an error
                    return;
                }

                // Trigger WooCommerce event for cart updates
                jQuery(document.body).trigger("added_to_cart", [
                    response.fragments,
                    response.cart_hash,
                    document.getElementById('add-to-cart'),
                ]);

                // Update the cart count
                document.getElementById('cart-count').innerText = response.cart_count; // Assuming this is provided

                // Optionally show a success message
                alert('Product added to cart successfully!');
            },
            error: function (xhr, status, error) {
                console.error('Error:', error); // Handle AJAX errors
            }
        });
    });
});

I tried with fetch(ajax_object.ajax_url before but with that I have to reload the page to see the cart update.



You need to sign in to view this answers

Leave feedback about this

  • Quality
  • Price
  • Service

PROS

+
Add Field

CONS

+
Add Field
Choose Image
Choose Video