cancel
Showing results for 
Search instead for 
Did you mean: 

Magento 2.3 : Load new custom items into Shopping Cart when an button is clicked

SOLVED

Magento 2.3 : Load new custom items into Shopping Cart when an button is clicked

1 ACCEPTED SOLUTION

Accepted Solutions

Re: Magento 2.3 : Load new custom items into Shopping Cart when an button is clicked

Hello @felix_schönher ,

Please add following code in your button_getcart.phtml

jQuery("#getCart").on("click", function(){
            jQuery.ajax({
                url:"http://192.168.10.106:8080/api/cart/",
                type:"GET", //First change type to method here
                headers: {
                  'X-Requested-With':  'XMLHttpRequest',
                  'Accept': '*/*',
                  'Cache-Control':'no-cache',
                },
                contentType: "application/json; charset=utf-8",
                data:
                {
                    "_customerID": 1, //for tests
                }
                success:function(response) {
			jQuery.ajax({
                		type: "post",
                		url: <?= $block->getUrl('vendor/extension/index') ?>,
                		data: {
				        productId: response.Product_ID
				    }
                		success: function (data) {
					console.log(data);
                		}
            		});
                },
                error:function(){
                  alert("An Error occurred. Try again later");
                }
            });
          }
      });

 And create your controller as :

<?php
namespace Vendor\Extension\Controller\Index;
use Magento\Framework\App\Action\Action;
use Magento\Framework\App\Action\Context;
use Magento\Framework\Data\Form\FormKey;
use Magento\Framework\Controller\Result\JsonFactory;
use Magento\Checkout\Model\Cart;
use Magento\Catalog\Model\Product;
class Post extends Action
{
    protected $formKey;   
    protected $cart;
    protected $product;
    public function __construct(
        Context $context,
	JsonFactory $resultJsonFactory,
        FormKey $formKey,
        Cart $cart,
        Product $product) {
            $this->formKey = $formKey;
	    $this->resultJsonFactory = $resultJsonFactory;
            $this->cart = $cart;
            $this->product = $product;      
            parent::__construct($context);
    }
    public function execute()
     { 
	$result = $this->resultJsonFactory->create();
        $productId = $this->getRequest()->getParam('productId');
        try {
		$params = array(
                    'form_key' => $this->formKey->getFormKey(),
                    'product' => $productId, 
                    'qty'   =>1
                );              
        	$product = $this->product->load($productId);       
       		$this->cart->addProduct($product, $params);
        	$this->cart->save();
		$result->setData(['message' => __("Product is added in cart")]);
		return $result;	
	} catch(\Exception $e) {
		$result->setData(['error' => __($e->getMessage())]);
		return $result;	
	}
     }
}

Note: Please change Vendor and Extension in both files as per your vendor and module name.

I hope this works for you. If still you face any issue, please let me know.

If it helps you, please give kudos and accept it as solution.

Regards.

 

View solution in original post

26 REPLIES 26

Re: Magento 2.3 : Load new custom items into Shopping Cart when an button is clicked

Hello @felix_schönher ,

Could you please provide the response which you are getting from this ajax call after success. It would be helpful for providing any solution.

Regards.

Re: Magento 2.3 : Load new custom items into Shopping Cart when an button is clicked

I get the following data back (Product ID [the ID saved in Magento 2], Amount, Price) and now i need to add this products to the cart in my Magento 2 shop.

Re: Magento 2.3 : Load new custom items into Shopping Cart when an button is clicked

Hello @felix_schönher ,

Please add following code in your button_getcart.phtml

jQuery("#getCart").on("click", function(){
            jQuery.ajax({
                url:"http://192.168.10.106:8080/api/cart/",
                type:"GET", //First change type to method here
                headers: {
                  'X-Requested-With':  'XMLHttpRequest',
                  'Accept': '*/*',
                  'Cache-Control':'no-cache',
                },
                contentType: "application/json; charset=utf-8",
                data:
                {
                    "_customerID": 1, //for tests
                }
                success:function(response) {
			jQuery.ajax({
                		type: "post",
                		url: <?= $block->getUrl('vendor/extension/index') ?>,
                		data: {
				        productId: response.Product_ID
				    }
                		success: function (data) {
					console.log(data);
                		}
            		});
                },
                error:function(){
                  alert("An Error occurred. Try again later");
                }
            });
          }
      });

 And create your controller as :

<?php
namespace Vendor\Extension\Controller\Index;
use Magento\Framework\App\Action\Action;
use Magento\Framework\App\Action\Context;
use Magento\Framework\Data\Form\FormKey;
use Magento\Framework\Controller\Result\JsonFactory;
use Magento\Checkout\Model\Cart;
use Magento\Catalog\Model\Product;
class Post extends Action
{
    protected $formKey;   
    protected $cart;
    protected $product;
    public function __construct(
        Context $context,
	JsonFactory $resultJsonFactory,
        FormKey $formKey,
        Cart $cart,
        Product $product) {
            $this->formKey = $formKey;
	    $this->resultJsonFactory = $resultJsonFactory;
            $this->cart = $cart;
            $this->product = $product;      
            parent::__construct($context);
    }
    public function execute()
     { 
	$result = $this->resultJsonFactory->create();
        $productId = $this->getRequest()->getParam('productId');
        try {
		$params = array(
                    'form_key' => $this->formKey->getFormKey(),
                    'product' => $productId, 
                    'qty'   =>1
                );              
        	$product = $this->product->load($productId);       
       		$this->cart->addProduct($product, $params);
        	$this->cart->save();
		$result->setData(['message' => __("Product is added in cart")]);
		return $result;	
	} catch(\Exception $e) {
		$result->setData(['error' => __($e->getMessage())]);
		return $result;	
	}
     }
}

Note: Please change Vendor and Extension in both files as per your vendor and module name.

I hope this works for you. If still you face any issue, please let me know.

If it helps you, please give kudos and accept it as solution.

Regards.

 

Re: Magento 2.3 : Load new custom items into Shopping Cart when an button is clicked

Hello, as what should I create the controller?

 

Re: Magento 2.3 : Load new custom items into Shopping Cart when an button is clicked

Please check my reply again, sorry due to some reason it was not posted.

Re: Magento 2.3 : Load new custom items into Shopping Cart when an button is clicked

Hello, i added everything, but the second ajax throws the error 404: not found. Any idea what i did false? (Edit) found the false code, now testing if everything works

Re: Magento 2.3 : Load new custom items into Shopping Cart when an button is clicked

Hello @felix_schönher 

Please check your routes.xml in etc/frontend folder of you module.

If that is fine then remove the generated folder by 

rm -rf generated/*

and then compile the code by 

bin/magento setup:di:compile

And lastly flush the magento cache by

bin/magento cache:flush 

Hope this will work for you. If you still have any issue, please let me know.

Regards.

Re: Magento 2.3 : Load new custom items into Shopping Cart when an button is clicked

Hello, 

 

i followed your instruction, but i can't find the url of the controller. But I noticed that I only have a module.xml in the etc folder with this code:

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
    <module name="MassiveArt_ShoppingCart" setup_version="1.0.0">
       <sequence>
            <module name="Magento_Checkout"/>
       </sequence>
    </module>
</config>

, but I dont have a routes.xml in my etc/frontend, do I need this file and if so, what is the code I need to write there. Sorry for this question, but I am very new to Magento 2

Re: Magento 2.3 : Load new custom items into Shopping Cart when an button is clicked

Okay, then you need to create a routes.xml in etc/frontend as :

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:App/etc/routes.xsd">
   <!--define id for frontend route is “standard”-->
   <router id="standard">
       <!--Route name-->
       <route id="example" frontName="example">
           <!--Module name-->
           <module name="Magestore_Example" />
       </route>
   </router>
</config>

Change you route id and frontName as per you module

I hope it work for you.

Regards