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.

7
  • 1
    So, It seems like you want add to cart product programmatically. Right? Commented Aug 16, 2019 at 7:03
  • Yes right, but it could be that the price is not the same as the price, that is saved in Magento. The Data i get from the REST API is (Price, ProductID [ID saved Magento] and amount) Commented Aug 16, 2019 at 7:10
  • Is there really nobody who can help me? Commented Aug 19, 2019 at 5:49
  • This is a great problem.
    – user82292
    Commented Aug 19, 2019 at 11:12
  • My company is struggling with this too.
    – user82292
    Commented Aug 19, 2019 at 11:12

2 Answers 2

1
+100

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.

2
  • Thank you very much, worked fine for me Commented Aug 20, 2019 at 11:55
  • I am always happy to help.
    – user82292
    Commented Aug 20, 2019 at 11:55
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!

1
  • Thanks for your answer, will try this in a moment! Commented Aug 20, 2019 at 5:31

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.