Magento2 Programmatically Update cart Item Quantity using ajax

Magento2 Programmatically Update cart Item using ajax .With out page refresh using Ajax and Jquery you can Update Magento2 Cart item Quantity1

  1. Html:

<div class=”product-secondary qty”>
<div class=”field “>
<div class=”control qty-wrapper”>
<span cart_id=”cart-<?= /* @escapeNotVerified */ $_item->getId() ?>-qty” class=”minus” onclick=”quantity_update(‘minus’,'<?php echo $_item->getPrice();?>’,'<?php echo $currencySymbol;?>’,<?php echo $product->getId(); ?>,<?php echo $_item->getId();?>,this);” data-field=”quant[1]”>
</span>
<input currencySymbol=”<?php echo $currencySymbol;?>” item_price=”<?php echo $_item->getPrice();?>” min=”1″ max=”1000″ onkeypress=”return isNumberKey(event)” id=”cart-<?= /* @escapeNotVerified */ $_item->getId() ?>-qty”
name=”cart[<?= /* @escapeNotVerified */ $_item->getId() ?>][qty]”
data-cart-item-id=”<?= $_item->getSku()?>”
value=”<?= /* @escapeNotVerified */ $_item->getQty() ?>”
type=”number”
size=”4″
title=”Qty”
class=”input-text qty”
data-validate=”{required:true,’validate-greater-than-zero’:true}”
data-role=”cart-item-qty”/>
<span onclick=”quantity_update(‘plus’,'<?php echo $_item->getPrice();?>’,'<?php echo $currencySymbol;?>’,<?php echo $product->getId(); ?>,<?php echo $_item->getId();?>,this);” cart_id=”cart-<?= /* @escapeNotVerified */ $_item->getId() ?>-qty” class=”plus” data-field=”quant[1]”></span>
</div>
</div>
</div>

2. Jquery:

function quantity_update(type,price,symbol,product_id,item_id,e)
   	{
   		
   	 require(['jquery', 'jquery/ui'], function($){
   		
   			if(type=='minus')
   			{
   				var now_quantity;
   				var cart_id=$(e).attr("cart_id");
   				var currentVal = parseInt($("#"+cart_id).val());
   				
   					if (!isNaN(currentVal)) {
   					   
   							
   							if(currentVal > $("#"+cart_id).attr('min')) {
   								
   								now_quantity=currentVal - 1;
   								$("#"+cart_id).val(now_quantity).change();
   								var total=now_quantity * price;
   								console.log(total)
   								$("#total_"+cart_id).html(symbol+total.toFixed(2));
   								
   							} 
   							if(parseInt($("#"+cart_id).val()) == $("#"+cart_id).attr('min')) {
   								$(this).attr('disabled', true);
   							}
   
   						
   					} else {
   						$("#"+cart_id).val(0);
   					}
   		        updateCart(product_id,now_quantity,item_id)
   			}
   			if(type=='plus')
   			{
   				var now_quantity;
   				var cart_id=$(e).attr("cart_id");
   				var currentVal = parseInt($("#"+cart_id).val());
   					if (!isNaN(currentVal)) {
   					   
   							
   							 if(currentVal < $("#"+cart_id).attr('max')) {
   								now_quantity=currentVal + 1;
   								$("#"+cart_id).val(now_quantity).change();
   								var total=now_quantity * price;
   								console.log(total)
   								$("#total_"+cart_id).html(symbol+total.toFixed(2));
   							}
   							if(parseInt($("#"+cart_id).val()) == $("#"+cart_id).attr('max')) {
   								$(this).attr('disabled', true);
   							}
   
   						
   					} else {
   						$("#"+cart_id).val(0);
   					}
   				updateCart(product_id,now_quantity,item_id)
   			}
   			//var form = $('form#form-validate');
   			
   			//form.submit();
   		
   		});
   		
   		 
   	}
   
      function updateCart(product_id,now_quantity,item_id)
      {   
          console.log(now_quantity);
   	   require(['jquery', 'jquery/ui'], function($){
   	   $.ajax({
   				url:'search/add/sellerquantityupdate',
   				type:'POST',
   				//dataType:'json',
   				showLoader: true,
   				data: {productid:product_id,qty:now_quantity,item_id:item_id},
   				success:function(response){
   					
   					
   					}
   			 });
   	   });

      }

3. Controller:


    namespace Medley\Search\Controller\Add;

    use Magento\Framework\App\Action\Context;
    use Magento\Framework\View\Result\PageFactory;

class Sellerquantityupdate extends \Magento\Framework\App\Action\Action
{
	
protected $cart;
protected $product;
 
public function __construct(
\Magento\Framework\App\Action\Context $context,
\Magento\Framework\Data\Form\FormKey $formKey,
\Magento\Checkout\Model\Cart $cart,
\Magento\Catalog\Model\Product $product,
array $data = []) {
	$this->formKey = $formKey;
	$this->cart = $cart;
	$this->product = $product;  	
	parent::__construct($context);
}
 
public function execute()
 {
  $post = $this->getRequest()->getPostValue();
  $productId =$post['productid'];     // Your Product Id
  $item_id =$post['item_id']; 
  $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
  $cartObj = $objectManager->get('\Magento\Checkout\Model\Cart');
  $current_quantity = $cartObj->getQuote()->getItemsQty();
  if(isset($post['qty']))
  {
	  
	  $itemData = [$item_id => ['qty' => $post['qty']]];
            $this->cart->updateItems($itemData);
			$this->cart->save();
			
			
	 // if($current_quantity>$post['qty'])
	 // {
		 // $new_quantity=$current_quantity-1;
	      /* $params = array(
            	'form_key' => $this->formKey->getFormKey(),
            	'product' => $productId,             	
                'qty'   =>$new_quantity   //quantity of product            	
        	); */
			
			//Load the product based on productID  
		   /*  $_product = $this->product->load($productId);   	
			$this->cart->updateProduct($_product, $params);
			$this->cart->save(); */ 
			
			/* $itemData = [$item_id => ['qty' => $new_quantity]];
            $this->cart->updateItems($itemData)->save(); */
			/* $itemData = [$item_id => ['qty' =>2]];
            $this->cart->updateItems($itemData);
			$this->cart->save(); */
	  //}
	  //else
	  //{
		  //$new_quantity=$current_quantity+1;
	      /* $params = array(
            	'form_key' => $this->formKey->getFormKey(),
            	'product' => $productId,             	
             'qty'   =>$new_quantity   //quantity of product            	
        	); */
			
		  //Load the product based on productID  
			/* $_product = $this->product->load($productId);   	
			$this->cart->updateProduct($_product, $params);
			$this->cart->save(); */
			/* $itemData = [$item_id => ['qty' => $new_quantity]];
            $this->cart->updateItems($itemData);
			$this->cart->save(); */

	  //}
	  
  }
  
   
         	
	
	
	
echo $totalItems = $cartObj->getQuote()->getItemsQty(); //Current cart Item counts
   
    }
}

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *

Show Buttons
Hide Buttons
Social Media Auto Publish Powered By : XYZScripts.com