I want to add more products to cart using ajax in magento 2 but it doesn't work. please help me to solve this problem here's my code

file ajax.phtml

require(['jquery'], function($){

    $(document).on("click",".tool-buttton-buy", function() {
        var addCartUrl = "<?php echo $block->getAjaxUrl().'ajaxcart/index/allcart' ?>";
        var searchIDs = $("input[name='product']").map(function(){return $(this).val();}).get();

        var jsonString = JSON.stringify(searchIDs);
            url: addCartUrl,
            type: 'POST',
            showLoader: true,
            cache: false,
            dataType: 'json',
            data: {productId : jsonString},
            success: function (data) {

file Controller Ajax

         $productAllId = json_decode($this->getRequest()->getParam('productId'));

foreach ($productAllId as $productId) {
    $params = array(
                'form_key' => $this->formKey->getFormKey(),
                'product' => $productId, 
                'qty'   =>1
    $product = $this->product->load($productId);       
    $this->cart->addProduct($product, $params);


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.