使用变体 ID 更新 Shopify 购物车时出现问题

问题描述 投票:0回答:1

Stackoverflow 社区您好,

我希望这篇文章能让您满意。我正在寻求帮助,以解决我目前在 Shopify 商店中遇到的问题,该问题与集成 Flatpickr 以进行日期选择以及使用所选变体 ID 更新购物车有关。

问题描述:

我使用 Flatpickr 实现了一个日期选择器,允许用户选择预订日期。该逻辑旨在根据所选日期范围确定适当的变体,并成功更新变体选择器并相应地显示价格。但是,当尝试将产品添加到购物车时,我遇到了“400 Bad Request”错误,表明发布到购物车的所选变体 ID 存在问题。

相关代码片段:

POST https://pro-sound-and-lighting.myshopify.com/cart/add.js?id=1%20Week&quantity=1&oseid=NSa28yXZX8Q7AskYMTv3hbju 400 (Bad Request)

代码上下文:

问题似乎与在 addToCart 函数期间如何构造变体 ID 并将其传递到购物车有关。 selectedVariantId 的格式或编码不正确,导致请求失败。

请求协助:

我非常感谢社区在识别和解决此问题方面提供的任何指导或帮助。以下是一些具体问题:

  1. 在将产品添加到购物车之前,如何正确格式化和编码 selectedVariantId?
  2. addToCart 函数中是否需要进行任何修改以确保请求 URL 的正确构造?

代码:

<!DOCTYPE html>
<html lang="en">
<head>
    <!-- Required meta tags -->
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">

    <!-- flatpickr -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/flatpickr/dist/flatpickr.min.css">

    <title>DateSelector</title>
</head>
<body class="vh-100">

<!-- Main Content -->
<div class="mx-auto" style="margin-top:2.71px;margin-bottom:2.71px;">
    <label class="form_label dates_label">Booking Dates</label>

    <form>
        <div class="date-picker-wrap date-pick-v3">

            <div class="date-picker-custom book-from">
                <label for="start_date" class="start-date">Book From:</label>
                <input type="text" id="start_date" class="form-control required" autocomplete="off" name="properties[Start Date]" form="product-form-{{ section.id }}" placeholder="" required>
            </div>

            <div class="booking-separator"></div>

            <div class="date-picker-custom book-to">
                <label for="end_date" class="end-date">Book To:</label>
                <input type="text" id="end_date" class="form-control required" autocomplete="off" name="properties[End Date]" form="product-form-{{ section.id }}" placeholder="" required>
            </div>

        </div>
    </form>

    <!-- Displayed Price -->
    <div class="price__regular">
        <span class="visually-hidden visually-hidden--inline">{{ 'products.product.price.regular_price' | t }}</span>
        <span id="displayed_price" class="price-item price-item--regular"> {{ money_price }} </span>
    </div>
</div>

<!-- Bootstrap JS -->
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>

<!-- flatpickr -->
<script src="https://cdn.jsdelivr.net/npm/flatpickr"></script>

<!-- Your Shopify script with Flatpickr integration -->
<script>
    document.addEventListener('DOMContentLoaded', function () {
        let selectedVariantId;

        const start_date = flatpickr("#start_date", {
            enableTime: false,
            allowInput: true,
            dateFormat: "d M",
            altInput: false,
            altFormat: "j F, Y",
            minDate: "today",
            disable: [
                function(date) {
                    // Disable Sundays
                    return date.getDay() === 0;
                }
            ],
            minTime: "09:00",
            maxTime: "17:00",
            onChange: function (sel_date, date_str) {
                // Set maxDate for end_date to one week from the selected start date
                const maxEndDate = new Date(sel_date);
                maxEndDate.setDate(maxEndDate.getDate() + 7); // Maximum 7 days from the selected start date
                end_date.set("minDate", date_str);
                end_date.set("maxDate", maxEndDate);
                updateProductVariant();
            }
        });

        const end_date = flatpickr("#end_date", {
            enableTime: false,
            allowInput: true,
            dateFormat: "d M",
            altInput: false,
            altFormat: "j F, Y",
            minDate: "today",
            disable: [
                function(date) {
                    // Disable Sundays
                    return date.getDay() === 0;
                }
            ],
            minTime: "09:00",
            maxTime: "17:00",
            onChange: function (sel_date, date_str) {
                updateProductVariant();
            }
        });

        function updateProductVariant() {
            // Logic to select product variant based on date range
            const start = start_date.selectedDates[0];
            const end = end_date.selectedDates[0];
            const daysDifference = Math.floor((end - start) / (24 * 60 * 60 * 1000)) + 1;

            let selectedVariant = "1 Night";
            if (daysDifference >= 3 && daysDifference <= 4) {
                selectedVariant = "2-3 Nights";
            } else if (daysDifference >= 5) {
                selectedVariant = "1 Week";
            }

            const variantSelector = document.querySelector('.select__select');

            // Find the option with the matching variant name
            const variantOption = Array.from(variantSelector.options).find(option => option.text === selectedVariant);

            if (variantOption) {
                // Set the selected variant in Shopify variant select
                variantSelector.value = variantOption.value;

                // Trigger a change event to ensure Shopify updates the product variant
                variantSelector.dispatchEvent(new Event('change'));

                // Fetch and update the displayed price based on the selected variant
                const displayedPriceElement = document.getElementById('displayed_price');
                const selectedVariantPrice = fetchVariantPrice(selectedVariant); // Implement this function
                displayedPriceElement.textContent = selectedVariantPrice;

                // Update the selectedVariantId
                selectedVariantId = variantSelector.value;
            }
        }

        const cartButton = document.getElementById('ProductSubmitButton-template--14892119556214__main');
        if (cartButton) {
            cartButton.addEventListener('click', addToCart);
        }

        function addToCart() {
            console.log('Selected Variant ID:', selectedVariantId);
        
            const encodedVariantId = encodeURIComponent(selectedVariantId);
            const addToCartUrl = `https://prosoundlighting.com.au/cart/add.js?id=${encodedVariantId}&quantity=1`;
        
            fetch(addToCartUrl, { method: 'POST' })
                .then(response => response.json())
                .then(data => {
                    console.log('Product added to cart:', data);
                    // Handle success, e.g., display a success message
                })
                .catch(error => {
                    console.error('Error adding product to cart:', error);
                    // Handle error, e.g., display an error message
                });
        }

        // Function to fetch the price of the selected variant
        function fetchVariantPrice(selectedVariant) {
            // Replace this with your logic to fetch the price based on the selected variant
            // Example: return a hardcoded price for the selected variant
            const regularPrice = parseFloat("{{ product.price | money_without_currency }}".replace(',', '')); // Replace with your actual Shopify liquid code

            switch (selectedVariant) {
                case "1 Night":
                    return formatPrice(regularPrice);
                case "2-3 Nights":
                    return formatPrice(regularPrice * 1.5);
                case "1 Week":
                    return formatPrice(regularPrice * 3);
                default:
                    return formatPrice(regularPrice * 3);
            }
        }

        // Helper function to format the price
        function formatPrice(price) {
            // Replace this with your logic to format the price (e.g., add currency symbol, decimal places, etc.)
            return "$" + price.toFixed(2);
        }
    });

</script>

</body>
</html>

我尝试了各种方法,但无法自行解决问题。社区的任何见解或建议都会非常有帮助。

提前感谢您的时间和帮助。

最诚挚的问候,

乔希

尝试了什么?

1。集成 Flatpickr 日期选择器:

  • 尝试包含 Flatpickr 日期选择器以允许用户选择日期。

2。根据日期更新变体选择器:

  • 逻辑已实现,以使用 Flatpickr 根据所选日期更新变体选择器。

3.正在获取变体 ID:

  • 已尝试获取与所选日期相对应的正确变体 ID。

4。将变体添加到购物车:

  • 创建 addToCart 函数是为了使用 Shopify 的 AJAX 端点将选定的变体添加到购物车。

期望什么?

1。用户可选择的日期:

  • 用户应该能够使用 Flatpickr 日期选择器选择日期。

2。动态变体选择器:

  • 变体选择器应根据所选日期动态更新。

3.正确的变体 ID:

  • 逻辑应正确确定与所选日期关联的变体 ID。

4。成功添加到购物车:

  • 将产品添加到购物车时,预期结果是使用正确的型号 ID 成功添加。

实际结果如何?

1。 Flatpickr 集成:

  • Flatpickr 日期选择器已成功集成,允许用户选择日期。

2。动态变体选择器:

  • 实现逻辑以根据所选日期动态更新变体选择器。

3.正在获取变体 ID:

  • 已尝试获取变体 ID,但从提供的 Shopify 代码中提取正确信息存在挑战。

4。将变体添加到购物车:

  • 虽然实现了 addToCart 功能,但获取正确的变体 ID 时出现问题,导致尝试将产品添加到购物车时出现错误请求错误。
javascript shopify liquid
1个回答
0
投票

感谢分享页面演示:

这里需要更新代码到当前页面。

替换这行代码

variantSelector.dispatchEvent(new Event('change'));

document.querySelector('variant-selects').dispatchEvent(new Event('change'));

还有 获取

addToCart
函数中的当前变体 ID

const encodedVariantId = encodeURIComponent(selectedVariantId);

const encodedVariantId = document.querySelector('[name="id"]').value;

© www.soinside.com 2019 - 2024. All rights reserved.