3

I am making my own module and now I added a button into it. If this button is clicked I want to get products with an AJAX request from a REST API (I already get my products, this is no problem).

Afterwards I want to load this products into the cart. This is were I have the main problem. I also want that the minicart gets updated. Is there a way to do this? I am very desperate.

This is my AJAX request (Yes I know that I currently not store the data I get back, I will add this when I have the solution for the problem I mentioned before):

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) {
                },
                error:function(){
                  alert("An Error occurred. Try again later");
                }
            });
          }
      });

This AJAX is in my view/frontend/templates/button_getcart.phtml file.

Can someboy please help me? I really need a solution for this and I am new to Magento 2.

Felix Schönherr
  • 501
  • 2
  • 26

2 Answers2

1

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; 
    }
     }
}

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.

0

You can update the mini cart via JS:

<script>
    require([
        'Magento_Customer/js/customer-data'
    ], function (customerData) {
        var sections = ['cart'];
        customerData.invalidate(sections);
        customerData.reload(sections, true);
    });
</script>

or @rohan-hapani has developed a controller for adding an array of items to the cart from an AJAX request and refreshing the mini cart. Please see the controller in his answers at the following posts.

magento 2 : Add multiple product to cart

Add multiple items to cart in Magento2

Please post your files and I'd be happy to help further. Good luck!

Mike Dubs
  • 505
  • 5
  • 18