'WooCommerce - How can I add multiple, products to cart using ajax with same add-to-cart-Button?
I am trying to use ajax to add multiple, different products to cart with one button click. The AddToCart-Button is living in SHOP before pagination. Ajax request sent multiple for example if I select 6 products and add to cart at a time the Ajax request sent 6 times and only 2 or 3 products added into cart not all of them. Everytime I add multiple products the code will add few of them.
and another bug is when I clicked add to cart for multiple product order the loader isn't work and cart NOT updated instantly I have to refresh the page so the cart will update and show me number of products on Cart Icon you can check on all functionality on the website: My Website
you have to login on it for using shop page here is the credentials:
login url:> https://myprojectstaging.net/development/firstline/my-account/
user: retailer
pass: myprojec_firstline.!
This is my function.php
file code:
function woocommerce_ajax_add_to_cart() {
$product_id = apply_filters('woocommerce_add_to_cart_product_id', absint($_POST['product_id']));
$quantity = apply_filters('woocommerce_add_to_cart_quantity', absint($_POST['quantity']));
$passed_validation = apply_filters('woocommerce_add_to_cart_validation', true, $product_id, $quantity);
$product_status = get_post_status($product_id);
if ($passed_validation && WC()->cart->add_to_cart($product_id, $quantity) && 'publish' === $product_status) {
do_action('woocommerce_ajax_added_to_cart', $product_id);
if ('yes' === get_option('woocommerce_cart_redirect_after_add')) {
wc_add_to_cart_message(array($product_id => $quantity), true);
}
WC_AJAX :: get_refreshed_fragments();
} else {
$data = array(
'error' => true,
'product_url' => apply_filters('woocommerce_cart_redirect_after_error', get_permalink($product_id), $product_id));
echo wp_send_json($data);
}
wp_die();
}
add_action('wp_ajax_woocommerce_ajax_add_to_cart', 'woocommerce_ajax_add_to_cart');
add_action('wp_ajax_nopriv_woocommerce_ajax_add_to_cart', 'woocommerce_ajax_add_to_cart');
And here is my jQuery for checkbox and Ajax:
var isChecked = false;
jQuery("body").on("change input", ".products li.product #add-to-cart-all", function(){
var len = jQuery(".products li.product #add-to-cart-all").filter(":checked").length;
if(len > 0){
jQuery(".bulk-add-to-cart").css("display","block");
}
else{
jQuery(".bulk-add-to-cart").css("display","none");
}
});
jQuery("body").on("click", ".bulk-add-to-cart a", function(){
jQuery(".products li.product #add-to-cart-all").filter(":checked").each(function(){
// alert(jQuery(this).val());
var product_id = jQuery(this).val();
var qty = jQuery(this).closest("li").find(".qty").val();
//alert(qty);
var data = {
action: "woocommerce_ajax_add_to_cart",
product_id: product_id,
quantity: qty,
};
$.ajax({
type: "post",
url: wc_add_to_cart_params.ajax_url,
data: data,
beforeSend: function (response) {
//alert("before");
},
complete: function (response) {
//alert("Complete");
},
success: function (response) {
if (response.error & response.product_url) {
console.log("add");
/* window.location = response.product_url;
return; */
} else {
alert("else");
// $(document.body).trigger("added_to_cart", [response.fragments, response.cart_hash, $thisbutton]);
}
},
});
});
});
Solution 1:[1]
I make it with my self here is the the code.
u can check it there as example...
script
let base_url = "https://myprojectstaging.net/development/firstline";
function multiAddToCart( productsData ) {
$.ajax({
url: base_url + '/wp-admin/admin-ajax.php',
type: 'POST',
dataType: 'JSON',
data: {
'action': 'multi_add_to_cart',
'items' : Object.assign({}, productsData)
},
success : function(response) {
$(document.body).trigger('wc_fragment_refresh'); // Refresh cart fragments
console.log('ajax-response',response);
$(".products li.product #add-to-cart-all").filter(":checked").each(function() {
$(this).prop('checked', false);
});
},
error : function(error) {
console.log(error);
}
});
}
$('.bulk-add-to-cart a').on('click', function() {
var productsData = [];
$(".products li.product #add-to-cart-all").filter(":checked").each(function() {
var product_id = jQuery(this).val();
var qty = jQuery(this).closest("li").find(".qty").val();
productsData.push({'id': product_id, 'qty': qty});
});
console.log('product-data',productsData);
multiAddToCart( productsData );
});
function.php
add_action('wp_ajax_multi_add_to_cart', 'multi_ajax_add_to_cart');
add_action('wp_ajax_nopriv_multi_add_to_cart', 'multi_ajax_add_to_cart');
function multi_ajax_add_to_cart() {
if (isset($_POST['items']) ) {
$item_keys = array();
foreach( $_POST['items'] as $item ) {
if( isset($item['id']) ) {
$item_qty = isset($item['qty']) && $item['qty'] > 1 ? $item['qty'] : 1;
$item_keys[] = WC()->cart->add_to_cart($item['id'], $item_qty);
}
}
echo json_encode($item_keys);
}
die();
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | M. Sufyan Sheikh |