javascript - Using AJAX to display how many of the current product is currently in the shopping cart -


really hoping can me out here.

what want achieve show little icon displaying how many of current product in shopping cart. e.g. user browsing product page "fresh oranges", user adds 2 fresh oranges cart want display "2" somewhere on product page. here code:

<?php foreach( wc()->cart->get_cart() $cart_item_key => $values ) { $_product = $values['data'];     if( $_product->id == get_the_id() ) { ?>     <div class="quantity-in-cart">         <span><?php echo $values['quantity'] ?></span>     </div> <?php } } ?> 

it's working if refresh product page, since i'm using ajax whole page doesn't refresh every time user adds product, need quantity field update more of product added cart.

if i'd appreciate it, questions or if none of wrote makes sense please let me know.

i've found workaround without needing use ajax suits needs.

display number of current product in cart in case user comes product page later. if empty, nothing display.

<div class="quantity-in-cart"> <span><?php foreach( wc()->cart->get_cart() $cart_item_key => $values ) {     $_product = $values['data'];         if( $_product->id == get_the_id() ) { ?><?php echo $values['quantity'] ?> <?php } } ?></span> </div> 

so if there none of current product in cart, nothing show in span. added js add 0:

$span = $(".quantity-in-cart span"); if($span.text() == ""){     $span.text("0"); }    

now default value of 0 set in span, if user adds more of current product cart, can add number in span quantity number selected user via add cart form.

$(".description .add-to-cart .add_to_cart_button").click(function() {     $('.quantity-in-cart span').text(parseint($('.quantity-in-cart span').text()) + parseint($('.quantity .qty').val())); }); 

...and i'm happy that. there's better way 0 in span if there none of current product in cart via php, i'm not great php. figured i'd share workaround on off chance looking achieve similar. still interested in seeing how accomplish using woocommerce's ajax functionality (there's code mini-cart used don't understand enough myself.)


Comments