admin管理员组

文章数量:1122846

I'm working on implementing a cross-selling feature on my product pages in Jumpseller. The goal is to display unrelated products (e.g., showing Windows OS products on other product pages) and allow customers to add these cross-sell products to the cart.

However, I’ve encountered the following issues:

  • When I use Jumpseller's GET method to fetch product information, it always retrieves the main product's data instead of the cross-sell product's data.
  • The cross-sell product's information in the "carrito de compras" (shopping cart) displays as undefined until the page is refreshed.

Here’s what I’ve tried so far:

  • I created a custom component to render the cross-sell product information.
  • I attempted to fetch the product details of the cross-sell product using its unique ID or SKU but could only get the main product’s information.
  • I tested adding the cross-sell product to the cart programmatically, but the cart updates incorrectly, showing undefined values until I refresh the page.

What I Need:

  • How can I fetch data for cross-sell products without overriding the main product's information?
  • How can I ensure the cross-sell product is displayed correctly in the cart without requiring a page refresh?

Additional Context:

I’m using Jumpseller’s custom coding capabilities to add this feature. The main issue seems to be that Jumpseller’s GET method prioritizes the main product and doesn’t handle unrelated product IDs well.

Any guidance or suggestions on how to implement this would be greatly appreciated!

product_info.liquid

<div class="col-12 col-md-6 offset-lg-1 {{ options.products_alignment_page }} product-info">
    <div class="row product-info__wrapper">
        {% include 'product_availability' %}

        {% if product.status == 'not-available' or product.stock == 0 and product.stock_unlimited == false %}
        <!-- Product Status -->
        {% include 'product_status' %}
        {% else %}
        {% unless options.disable_shopping == true %}
        <!-- Product Form -->
        {% include 'product_form' %}
        {% endunless %}
        {% endif %}

        <!-- Windows Cross-Selling Component -->
        {% for category in product.categories %}
            {% if category.name == "Computadores Armados" %}
                {% include 'cart_cross_windows' %}
                {% break %}
            {% endif %}
        {% endfor %}

        {% if options.pp_payments == true %}
        {% include 'product_payments' %}
        {% endif %}

        {% if product.description != blank and options.pp_description_position == 'middle' %}
        {% include 'product_description' %}
        {% endif %}

        {% if product.fields.size > 0 and options.pp_customfields == true and options.pp_customfields_position == 'table' %}
        {% include 'product_fields' %}
        {% endif %}

        {% if options.pp_accordion == true %}
        <!-- Product Accordion -->
        {% include 'product_accordion' %}
        {% endif %}

        {% if options.pp_share == true %}
        {% include 'product_share' %}
        {% endif %}
    </div>
</div>
<!-- end .product-info -->

cross_selling_windows.liquid

<!-- Cross-Selling Section -->
<div class="cart-cross" style="padding: 20px; background: white; border-radius: 10px; margin: 20px auto;">
    <div class="col-12">
        <h2 style="font-size: 16px;">{% t "AÑADIR LICENCIA ORIGINAL DE MICROSOFT WINDOWS AL EQUIPO" %}</h2>
    </div>
    <div class="col-12" style="padding: 10px;">
        <div class="row">
            {% assign system_operating_category = store.category['sistema-operativo'] %}

            {% for product in system_operating_category.products %}
                {% if product.sku == "WIN003" or product.sku == "WIN004" %}
                <!-- Cross-Selling Product Block -->
                <div class="col-12 store-product store-product--cross" style="margin-bottom: 20px;">
                    <div class="store-product__container" style="display: flex; align-items: center; padding: 20px; border: 1px solid #ddd; background-color: #f9f9f9; border-radius: 10px;">
                        
                        <!-- Product Image -->
                        <a href="{{ product.url }}" class="store-product__image" style="margin-right: 15px;">
                            {% if product.images.size > 0 %}
                            <img src="{{ product.images.first | thumb:'70x70' }}" alt="{{ product.name }}" style="width: 70px; height: 70px; border-radius: 5px;">
                            {% else %}
                            <img src="{{ 'placeholder-image-product-page-thumb_square.jpg' | asset }}" alt="Imagen no disponible" style="width: 70px; height: 70px; border-radius: 5px;">
                            {% endif %}
                        </a>

                        <!-- Product Info -->
                        <div class="store-product__info" style="flex-grow: 1;">
                            <h3 style="font-size: 16px; margin: 0;">{{ product.name | default: "Producto desconocido" }}</h3>
                            {% if product.discount > 0 %}
                            <div style="margin-top: 5px;">
                                <span style="font-size: 14px; color: green;">{{ product.price | minus:product.discount | price }}</span>
                                <small style="text-decoration: line-through; color: red;">{{ product.price | price }}</small>
                            </div>
                            {% else %}
                            <div style="margin-top: 5px;">
                                <span style="font-size: 14px;">{{ product.price | default: 0 | price }}</span>
                            </div>
                            {% endif %}
                        </div>

                        <!-- Add to Cart Form -->
                        <form class="product-form" 
                              data-id="{{ product.id }}" 
                              data-name="{{ product.name }}" 
                              data-parent-id="{{ parent_product_id }}" 
                              style="display: flex; align-items: center;">
                            <input type="number" 
                                   name="quantity" 
                                   value="1" 
                                   min="1" 
                                   style="width: 50px; margin-right: 10px; text-align: center;" 
                                   {% if product.stock_unlimited %} max="99999" 
                                   {% else %} max="{{ product.stock | default: 1 }}" 
                                   {% endif %}>
                            <button type="submit" class="button" style="padding: 5px 10px; background-color: #007bff; color: white; border: none; border-radius: 5px;">
                                Agregar al carrito
                            </button>
                        </form>
                    </div>
                </div>
                {% endif %}
            {% endfor %}
        </div>
        <span style="font-size: 13px;">{% t "Al hacer clic en cualquiera de las dos opciones, este producto se agregará automáticamente a su carrito de compras." %}</span>
    </div>
</div>

<!-- JavaScript -->
<script>
// Function to Add Product to Cart
function addProduct(productId, productName, quantity, parentProductId = null) {
    console.log('Adding product to cart:', { productId, productName, quantity, parentProductId });

    if (!productId || !quantity) {
        alert('Error: Información del producto incompleta.');
        console.error('Invalid product data:', { productId, productName, quantity });
        return;
    }

    fetch('.json', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
            id: productId,
            name: productName,
            quantity: quantity,
            parentId: parentProductId // Optional: Links the cross-sell item to the PC product
        }),
    })
    .then((response) => {
        if (!response.ok) {
            throw new Error(`Failed to add product: ${response.status} ${response.statusText}`);
        }
        return response.json();
    })
    .then((data) => {
        console.log('Product successfully added to cart:', data);
        fetchCartSummary(); // Refresh the cart summary
    })
    .catch((error) => {
        console.error('Error adding product to cart:', error.message);
    });
}

// Function to Fetch and Update Cart Summary
function fetchCartSummary() {
    console.log('Fetching cart summary...');
    fetch('.json', {
        method: 'GET',
        headers: { 'Content-Type': 'application/json' },
    })
    .then((response) => response.json())
    .then((cartData) => {
        console.log('Cart summary received:', cartData);

        const cartItemsContainer = document.getElementById('cart-summary');
        cartItemsContainer.innerHTML = ''; // Clear existing items

        if (cartData && cartData.items) {
            cartData.items.forEach((item) => {
                const isCrossSell = item.parentId !== null; // Check if it's a cross-sell item
                cartItemsContainer.innerHTML += `
                    <div style="margin-bottom: 10px;">
                        <span>${item.name || 'Producto desconocido'}</span>
                        <span>${item.quantity || 0} x ${item.price || 'N/A'}</span>
                        ${isCrossSell ? '<small>(Añadido como adicional)</small>' : ''}
                    </div>
                `;
            });
        } else {
            cartItemsContainer.innerHTML = '<p>No hay productos en el carrito.</p>';
        }
    })
    .catch((error) => {
        console.error('Error fetching cart summary:', error.message);
    });
}

// Add Event Listener for Cross-Selling Forms
document.querySelectorAll('.product-form').forEach((form) => {
    form.addEventListener('submit', function (e) {
        e.preventDefault(); // Prevent default form submission

        const productId = form.dataset.id;
        const productName = form.dataset.name;
        const quantity = form.querySelector('[name="quantity"]').value;
        const parentProductId = form.dataset.parentId || null;

        addProduct(productId, productName, quantity, parentProductId);
    });
});
</script>

If I go to the Windows 11 product page and add the same Windows version using the cross-selling component, everything works well because both items are the same.

enter image description here

本文标签: