cancel
Showing results for 
Search instead for 
Did you mean: 

replace data-post data-action with form for Jquery ajax

   Did you know you can see the translated content as per your choice?

Translation is in progress. Please check again after few minutes.

replace data-post data-action with form for Jquery ajax

<a href="#" class="action towishlist actions-secondary " title="Wish List" aria-label="Wish List" data-post="{&quot;action&quot;:&quot;http:\/\/www.test.in\/wishlist\/index\/add\/&quot;,&quot;data&quot;:{&quot;product&quot;:&quot;1&quot;,&quot;uenc&quot;:&quot;aHR0cDovL3BhcGF5YS5rb2Rld29yay5pbi9qZXdlbHJ5Lmh0bWw,&quot;}}" data-action="add-to-wishlist" role="button">
     <span>Wish List</span>
</a>

can somebody please tell me how to change this to form so that i need to have it a ajax call to add to wishlist from catalog/product/list.phtml

 

I have written a plugin to send back json response on adding to wishlist, it takes me to a new page with the ajax response. 

 

<?php

namespace Namespace\Vendor\Controller\Plugin;

use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Framework\App\Action;
use Magento\Framework\Data\Form\FormKey\Validator;
use Magento\Framework\Exception\NotFoundException;
use Magento\Framework\Exception\NoSuchEntityException;
use Magento\Framework\Controller\ResultFactory;

class AddPlugin extends \Magento\Wishlist\Controller\Index\Add {

    /**
     * @var \Magento\Wishlist\Controller\WishlistProviderInterface
     */
    protected $wishlistProvider;

    /**
     * @var \Magento\Customer\Model\Session
     */
    protected $_customerSession;

    /**
     * @var ProductRepositoryInterface
     */
    protected $productRepository;

    /**
     * @var Validator
     */
    protected $formKeyValidator;
    protected $resultJsonFactory;

    public function __construct(
    Action\Context $context, \Magento\Customer\Model\Session $customerSession, \Magento\Wishlist\Controller\WishlistProviderInterface $wishlistProvider, ProductRepositoryInterface $productRepository, Validator $formKeyValidator, \Magento\Framework\Controller\Result\JsonFactory $resultJsonFactory
    ) {
        $this->_customerSession = $customerSession;
        $this->wishlistProvider = $wishlistProvider;
        $this->productRepository = $productRepository;
        $this->formKeyValidator = $formKeyValidator;

        $this->resultJsonFactory = $resultJsonFactory;

        parent::__construct(
                $context, $customerSession, $wishlistProvider, $productRepository, $formKeyValidator
        );
    }

    public function aroundExecute($subject, $procede) {
        
        $response = [];
        
        /** @var \Magento\Framework\Controller\Result\Redirect $resultRedirect */
        $resultRedirect = $this->resultFactory->create(ResultFactory::TYPE_REDIRECT);
        if (!$this->formKeyValidator->validate($this->getRequest())) {
            return $resultRedirect->setPath('*/');
        }

        $wishlist = $this->wishlistProvider->getWishlist();
        if (!$wishlist) {
            throw new NotFoundException(__('Page not found.'));
        }

        $session = $this->_customerSession;

        $requestParams = $this->getRequest()->getParams();

        if ($session->getBeforeWishlistRequest()) {
            $requestParams = $session->getBeforeWishlistRequest();
            $session->unsBeforeWishlistRequest();
        }

        $productId = isset($requestParams['product']) ? (int)$requestParams['product'] : null;
        if (!$productId) {
            $resultRedirect->setPath('*/');
            return $resultRedirect;
        }

        try {
            $product = $this->productRepository->getById($productId);
        } catch (NoSuchEntityException $e) {
            $product = null;
        }

        if (!$product || !$product->isVisibleInCatalog()) {
//            $this->messageManager->addErrorMessage(__('We can\'t specify a product.'));
            $response = [
                        'status' => 'ERROR',
                        'msg' => __('We can\'t specify a product.'),
                    ];
            $resultRedirect->setPath('*/');
            return $resultRedirect;
        }

        try {
            $buyRequest = new \Magento\Framework\DataObject($requestParams);

            $result = $wishlist->addNewItem($product, $buyRequest);
            if (is_string($result)) {
                throw new \Magento\Framework\Exception\LocalizedException(__($result));
            }
            $wishlist->save();
            $response = [
                        'status' => 'OK',
                        'msg' => $product->getName().__(' Added to wishlist'),
                    ];
            $this->_eventManager->dispatch(
                'wishlist_add_product',
                ['wishlist' => $wishlist, 'product' => $product, 'item' => $result]
            );

            $referer = $session->getBeforeWishlistUrl();
            if ($referer) {
                $session->setBeforeWishlistUrl(null);
            } else {
                $referer = $this->_redirect->getRefererUrl();
            }

            $this->_objectManager->get('Magento\Wishlist\Helper\Data')->calculate();

//            $this->messageManager->addComplexSuccessMessage(
//                'addProductSuccessMessage',
//                [
//                    'product_name' => $product->getName(),
//                    'referer' => $referer
//                ]
//            );
//            
        } catch (\Magento\Framework\Exception\LocalizedException $e) {
            $response = [
                        'status' => 'ERROR',
                        'msg' => __('We can\'t add the item to Wish List right now: %1.', $e->getMessage()),
                    ];
            
        } catch (\Exception $e) {
            $response = [
                        'status' => 'ERROR',
                        'msg' =>__('We can\'t add the item to Wish List right now.'),
                    ];
        }

//        $resultRedirect->setPath('*', ['wishlist_id' => $wishlist->getId()]);
        return $this->resultJsonFactory->create()->setData($response);
    }

}

 

and also any suggestions appreciated.

 

Thank you

3 REPLIES 3

Re: replace data-post data-action with form for Jquery ajax

Actually, it creates small form. You can check this here

vendor/magento/magento2-base/lib/web/mage/dataPost.js

Re: replace data-post data-action with form for Jquery ajax

Hello @sylvester_mag

 

Please check below module

 

https://www.tigren.com/magento-2-extensions/ajax-suite-magento-2/

 

Hope it will help you.


Problem solved? Click Kudos & Accept as Solution!
Sunil Patel
Magento 2 Certified Professional Developer & Frontend Developer

Re: replace data-post data-action with form for Jquery ajax

Hi, did you find a sollution for this?