简体   繁体   English

使用 ajax/fetch 从购物车中删除 Woocommerce 产品

[英]Remove Woocommerce product from cart with ajax/fetch

I have a problem with removing products from the cart in Woocommerce and I think it has to do with WC_Cart::remove_cart_item .我在 Woocommerce 从购物车中删除产品时遇到问题,我认为这与WC_Cart::remove_cart_item I only get these error messages:我只收到这些错误消息:

POST http://localhost:3000/esport/wp-admin/admin-ajax.php
[HTTP/1.1 500 Internal Server Error 3046ms]

SyntaxError: JSON.parse: unexpected end of data at line 1 column 1 of the JSON data

The products are looped over from my latte (php) file and adding a data-key attribute to each <li> element.这些产品是从我的 latte (php) 文件循环过来的,并向每个<li>元素添加了一个data-key属性。

{var $cart_items = WC()->cart->get_cart()}
<section class="sidebar-checkout">
        <div class="sidebar-checkout__header">
            <h3 n:ifcontent>Varukorg</h3>
            <button class="cart-checkout-close"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" class="w-8 mr-4 icon-close"><path class="secondary" fill-rule="evenodd" d="M15.78 14.36a1 1 0 0 1-1.42 1.42l-2.82-2.83-2.83 2.83a1 1 0 1 1-1.42-1.42l2.83-2.82L7.3 8.7a1 1 0 0 1 1.42-1.42l2.83 2.83 2.82-2.83a1 1 0 0 1 1.42 1.42l-2.83 2.83 2.83 2.82z"></path></svg></button>
        </div>
        <ul class="sidebar-cart" n:if="$cart_items">
            <li n:foreach="$cart_items as $cart_item_key => $cart_item" class="sidebar-cart__item" data-key="{$cart_item_key}">
                {var $product = $cart_item['data']}
                {var $img_src = wp_get_attachment_image_url($product->get_image_id(), 'thumbnail')}
                {var $image_alt = get_post_meta($attachment_id, "_wp_attachment_image_alt", TRUE)}
                <img src="{$img_src}" alt="{$image_alt}" decoding="async" loading="lazy">
                <a href="{get_permalink($product->get_id())}">{$product->get_name()}</a>
                <button class="remove_from_cart_button"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" class="w-8 mr-4 icon-trash"><path class="primary" d="M5 5h14l-.89 15.12a2 2 0 0 1-2 1.88H7.9a2 2 0 0 1-2-1.88L5 5zm5 5a1 1 0 0 0-1 1v6a1 1 0 0 0 2 0v-6a1 1 0 0 0-1-1zm4 0a1 1 0 0 0-1 1v6a1 1 0 0 0 2 0v-6a1 1 0 0 0-1-1z"></path><path class="secondary" d="M8.59 4l1.7-1.7A1 1 0 0 1 11 2h2a1 1 0 0 1 .7.3L15.42 4H19a1 1 0 0 1 0 2H5a1 1 0 1 1 0-2h3.59z"></path></svg></button>
            </li>
            <div class="widget_shopping_cart_content"></div>
        </ul>
</section>

The key attributes are picked up by my javascript file and then sent by the fetch function and received by the wp_ajax_ custom function.关键属性由我的 javascript 文件拾取,然后由提取 function 发送并由wp_ajax_自定义 function 接收。

const remove_from_cart_button = document.querySelectorAll('.remove_from_cart_button');
remove_from_cart_button.forEach(e => {
    e.addEventListener('click', async e => {
        const key = e.target.closest('.sidebar-cart__item').dataset.key;
        try {
            const response = await fetch('/esport/wp-admin/admin-ajax.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded'
                },
                body: 'action=my_custom_action&cart_item_key=' + key
                }
            );
            const data = await response.json();
            console.log('data', data);
        } catch (error) {
            console.error(error)
        }
    }
)})

And my final ajax function:我的最终 ajax function:

add_action('wp_ajax_my_custom_action', 'my_custom_action_callback');
add_action('wp_ajax_nopriv_my_custom_action', 'my_custom_action_callback');

function my_custom_action_callback() {
    $cart_item_key = $_POST['cart_item_key'];
    foreach(WC()->cart->get_cart() as $key => $item) {
        if ($key == $cart_item_key) {
            WC()->cart->remove_cart_item($key);
            wp_send_json_success(array('message' => 'Cart item removed successfully'));
        }
    }
  
}

If I remove WC()->cart->remove_cart_item($key);如果我删除WC()->cart->remove_cart_item($key); It sends back the json message without problem.它毫无问题地发回 json 消息。 I have tried using woocommerce_remove_cart_item directly in the action fetch but I also get an error there.我尝试直接在action提取中使用woocommerce_remove_cart_item但我也在那里遇到错误。

add wp_die() at the end of your function在 function 的末尾添加wp_die()

add_action('wp_ajax_my_custom_action', 'my_custom_action_callback');
add_action('wp_ajax_nopriv_my_custom_action', 'my_custom_action_callback');

function my_custom_action_callback() {
    $cart_item_key = $_POST['cart_item_key'];
    foreach(WC()->cart->get_cart() as $key => $item) {
        if ($key == $cart_item_key) {
            WC()->cart->remove_cart_item($key);
            wp_send_json_success(array('message' => 'Cart item removed successfully'));
            wp_die();
        }
    }
    
}

Try replacing your function with this one:尝试用这个替换您的 function:


add_action('wp_ajax_my_custom_action', 'my_custom_action_callback');
add_action('wp_ajax_nopriv_my_custom_action', 'my_custom_action_callback');

function my_custom_action_callback() {

    if( empty($_POST['cart_item_key']) ){
        wp_send_json_error(array('message' => 'Cart item key empty!'));
    }

    $cart_item_key = $_POST['cart_item_key'];

    try {
        if(WC()->cart->remove_cart_item($cart_item_key)){
            wp_send_json_success(array('message' => 'Cart item removed successfully'));
        }else{
            wp_send_json_error(array('message' => 'Something was wrong for key '.$cart_item_key));
        }
    } catch (Exception $e) {
        wp_send_json_error(array('message' => $e->getMessage()));
    }
}

This code will check the cart key, check if the item was removed and catch any exceptions and return the error message.此代码将检查购物车密钥,检查该项目是否已被删除并捕获任何异常并返回错误消息。 This is not a fix to your problem but a way to figure out what's happening.不是解决您的问题的方法,而是一种弄清楚正在发生的事情的方法。 It's very unusual to get the code 500 without any traces in the error log.在错误日志中没有任何痕迹地获取代码 500 是非常不寻常的。 This should at least prevent the 500 and print the error.这至少应该可以防止 500 并打印错误。 remove_cart_item is a very short and simple function that should not cause any problems but there are 2 hooks called inside and some other code could be causing this. remove_cart_item是一个非常简短的 function ,应该不会引起任何问题,但内部调用了 2 个挂钩,其他一些代码可能会导致此问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM