How To Add The Product In The Cart Using AJAX Without Refreshing The Page In WooCommerce?
Please add the following code to ensures the WooCommerce cart functions efficiently & Add the product in the cart without refreshing the page.
// JavaScript for updating the cart via AJAX
document.addEventListener('DOMContentLoaded', function () {
const $ = jQuery;
// Intercept the update cart button click
$('button[name="update_cart"]').off('click').on('click', function (e) {
e.preventDefault(); // Stop default button action
const $form = $(this).closest('form.woocommerce-cart-form');
if ($form.length) {
updateCartAjax($form); // Trigger AJAX cart update
}
});
// Trigger AJAX update when quantity changes
$(document.body).on('change', '.qty', function () {
const $form = $(this).closest('form.woocommerce-cart-form');
if ($form.length) {
updateCartAjax($form); // Trigger AJAX cart update
}
});
// AJAX function to update the cart
function updateCartAjax($form) {
$.ajax({
type: 'POST',
url: wc_add_to_cart_params.ajax_url, // WooCommerce AJAX URL
data: $form.serialize() + '&action=update_cart', // Serialize form data
beforeSend: function () {
$form.block({
message: null,
overlayCSS: {
background: '#fff',
opacity: 0.6
}
});
},
success: function () {
$(document.body).trigger('updated_cart_totals'); // Trigger cart update event
updateCartTotals(); // Refresh cart totals
},
complete: function () {
$form.unblock(); // Remove loading indicator
}
});
}
// Function to update cart totals via AJAX
function updateCartTotals() {
$.ajax({
url: wc_add_to_cart_params.ajax_url,
type: 'POST',
data: { action: 'get_cart_totals' },
success: function (response) {
// Update cart total elements dynamically
if (response.cart_count !== undefined) {
$('.cart-price-final .price-itemno:first').html(response.cart_count + ' items');
}
if (response.cart_total !== undefined) {
$('.cart-price-final .price-itemno:last').html(response.cart_total);
$('.order-total .amount').html(response.cart_total);
}
if (response.cart_subtotal !== undefined) {
$('.cart-subtotal .amount').html(response.cart_subtotal);
}
}
});
}
// Update totals on cart events
$(document.body).on('updated_cart_totals added_to_cart removed_from_cart', function () {
updateCartTotals();
});
// Initial cart totals update
updateCartTotals();
});
// PHP: AJAX handler for updating the cart
add_action('wp_ajax_update_cart', 'handle_update_cart');
add_action('wp_ajax_nopriv_update_cart', 'handle_update_cart');
function handle_update_cart() {
$cart_updated = false;
if (!empty($_POST['cart'])) {
foreach ($_POST['cart'] as $cart_item_key => $values) {
if (!empty($values['qty'])) {
WC()->cart->set_quantity($cart_item_key, $values['qty'], true);
$cart_updated = true;
}
}
}
if ($cart_updated) {
WC()->cart->calculate_totals();
}
wp_send_json_success();
}
// PHP: AJAX handler for retrieving cart totals
add_action('wp_ajax_get_cart_totals', 'get_cart_totals');
add_action('wp_ajax_nopriv_get_cart_totals', 'get_cart_totals');
function get_cart_totals() {
wp_send_json(array(
'cart_count' => WC()->cart->get_cart_contents_count(),
'cart_total' => strip_tags(wc_price(WC()->cart->get_total())),
'cart_subtotal' => strip_tags(wc_price(WC()->cart->get_subtotal())),
));
}
JavaScript Updates:
PHP Handlers:
领英推荐
Improved User Experience:
This will prevent page from refreshing and add the product to the cart with AJAX & WooCommerce.
Looking to Build or Upgrade Your E-commerce Store?
?? Contact us today at [email protected]
?? Visit us at: https://w3nuts.co.uk/