skip to Main Content

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. 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.

{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.

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:

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); It sends back the json message without problem.
I have tried using woocommerce_remove_cart_item directly in the action fetch but I also get an error there.

2

Answers


  1. add wp_die() at the end of your 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'));
                wp_die();
            }
        }
        
    }
    
    Login or Signup to reply.
  2. Try replacing your function with this one:

    
    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. This should at least prevent the 500 and print the error. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search