I am using following code to add product to cart on my button click. It works fine (product is added to cart), but the count in mini cart is only updated after second add. First time I click add, there is no update visible in cart mini icon (unless I refresh the page).
I use default WordPress theme.
php:
add_action('wp_ajax_map_woo_add_to_cart', 'map_woo_add_to_cart');
function map_woo_add_to_cart(){
if(isset($_POST['product_id'])){
$product_id = $_POST['product_id'];
ob_start();
$quantity = 1;
$passed_validation = apply_filters( 'woocommerce_add_to_cart_validation', true, $product_id, $quantity );
$product_status = get_post_status( $product_id );
$added = WC()->cart->add_to_cart( $product_id, $quantity );
if ( $passed_validation && $added && 'publish' === $product_status ) {
ob_start();
woocommerce_mini_cart();
$mini_cart = ob_get_clean();
$data = array(
'fragments' => apply_filters(
'woocommerce_add_to_cart_fragments',
array(
'div.widget_shopping_cart_content' => '<div class="widget_shopping_cart_content">' . $mini_cart . '</div>',
)
),
'cart_hash' => WC()->cart->get_cart_hash(),
'ajax_nonce' => wp_create_nonce( 'map_woo-security-nonce' ),
);
wp_send_json_success( $data );
} else {
$data = array(
'message' => __( 'The product was not added to the cart', MAP_WOO_TEXTDOMAIN ),
'product_url' => apply_filters( 'woocommerce_cart_redirect_after_error', get_permalink( $product_id ), $product_id ),
'product_id' => $product_id,
);
wp_send_json_error( $data );
}
}
}
javascript:
function addProductToCart(postId, data){
const params = new URLSearchParams();
params.append("action", 'map_woo_add_to_cart');
params.append("product_id", postId);
var xhrRequest = new XMLHttpRequest();
xhrRequest.onreadystatechange = function() {
if (this.readyState == 4) {
var result = JSON.parse(this.responseText);
console.log(result);
if ( result.data.fragments ) {
jQuery( document.body ).trigger( 'wc_fragment_refresh' );
jQuery( document.body ).trigger( 'added_to_cart', [ result.data.fragments, result.data.cart_hash ] );
}
}
}
xhrRequest.onerror = function(e) {
console.log('Error add_to_cart: ' + e);
};
xhrRequest.open('POST', settings.ajax_url);
xhrRequest.setRequestHeader("Content-Type", 'application/x-www-form-urlencoded');
xhrRequest.send(params);
}