I have added a removal link to the checkout for each product. This part works fine. Problem is; upon removal, the page is "scrolled to top".
I would like to change this by adding AJAX to the removal process. I’ve tried, but without success. In other words; when clicking on the removal link, the refresh should happen in the background and the customer stays on the same section.
This is the code I am working with:
add_filter( 'woocommerce_checkout_cart_item_quantity', 'link_to_remove_item_from_checkout', 20, 3 );
function link_to_remove_item_from_checkout( $quantity_html, $cart_item, $cart_item_key ) {
$remove_item = apply_filters( 'woocommerce_cart_item_remove_link', sprintf (
'<a style="text-decoration:underline" href="%s" rel="nofollow" title="Remove from Order" class="remove-product-from-checkout">Remove</a>',
esc_url(wc_get_cart_remove_url($cart_item_key)),
__('Remove from Order', 'woocommerce'),
esc_attr($cart_item['product_id']),
esc_attr($cart_item['data']->get_sku())
), $cart_item_key);
return '<br><strong class="product-quantity">' . sprintf('<b>Qty:</b> %s', $cart_item['quantity']) . '</strong> '.$remove_item.'<br clear="all">';
}
add_action('wp_ajax_woo_get_ajax_data', 'remove_product_from_checkout');
add_action('wp_ajax_nopriv_woo_get_ajax_data', 'remove_product_from_checkout');
function remove_product_from_checkout() {
if ( isset( $_POST['$remove_item']) ) {
$remove_product = sanitize_key( $_POST['$remove_item']);
WC()->session->set('product_id', $remove_product);
echo json_encode($remove_item);
}
die();
}
This is the script which I am not sure how to modify to make this work with a link.
add_action('wp_footer', 'script_for_removing_product_on_checkout', 10, 0);
function script_for_removing_product_on_checkout(){
if (!is_checkout()) return;
?>
<script type="text/javascript">
jQuery( function($){
$('form.checkout').on('change', 'remove_product', function(e){
e.preventDefault();
var p = $(this).val();
$.ajax({
type: 'POST',
url: wc_checkout_params.ajax_url,
data:{
'action': 'woo_get_ajax_data',
'packing': p,
},
success: function (result){
$('body').trigger('update_checkout');
},
error: function(error){
}
});
});
});
</script>
<?php
}
2
Answers
Your code contains some mistakes.
To remove a product (item) from checkout using AJAX, you can use:
Try this?