3

I'm trying to implement adding product to wishlist using ajax. I have managed to do this but I can't get the success message from response ("You have added X product to wishlist").

require([

'jquery',

], function(jQuery){

    (function($) {

        $(document).ready(function(){

            $('#product-addtowishlist-button').click(function(){
                var parsedJson = $.parseJSON($(this).attr( "dtcustom" ));
                var url = parsedJson.action;
                var data1 = parsedJson.data;
                var current_prod = data1.product;
                var current_uenc = data1.uenc;

                formKey = $('input[name="form_key"]').val();
                var data = {
                    action   : "add-to-wishlist",
                    form_key : formKey,
                    product  : current_prod,
                    uenc     : current_uenc
                }


                $.ajax({

                    url: url,
                    data: data,

                    beforeSend: function(xhr, options) {
                        jQuery('#loading').show();
                    },

                    success: function(data,textStatus,jqXHR){
                        if (textStatus == 'success') {
                            //can't find success message in response html
                        }
                    }
                });
                return false;

            });

        });

    })(jQuery);

});

Adding product to wishlist usually redirects to Wishlist page, displaying a success message. But in this case response data does not contain that message.

Is there a better way to do the ajax call? Am I missing something here?

1

1 Answer 1

4

First of all override your wish-list add controller by your custom module. after that use below code for your add controller. Currently I'm using Vendor\Module as my custom module, you can use anything.

<?php
/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */
namespace Vendor\Module\Controller\Wishlist\Index;

/**
 * @SuppressWarnings(PHPMD.CouplingBetweenObjects)
 */
class Add extends \Magento\Wishlist\Controller\Index\Add
{

    public function execute()
    {

        /** @var \Magento\Framework\Controller\Result\Redirect $resultRedirect */
        //$resultRedirect = $this->resultFactory->create(ResultFactory::TYPE_REDIRECT);
            //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.'));
            $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));
            }

            if ($wishlist->isObjectNew()) {
                $wishlist->save();
            }
            $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::class)->calculate();

            /*$this->messageManager->addComplexSuccessMessage(
                'addProductSuccessMessage',
                [
                    'product_name' => $product->getName(),
                    'referer' => $referer
                ]
            );*/
        } catch (\Magento\Framework\Exception\LocalizedException $e) {
            /*$this->messageManager->addErrorMessage(
                __('We can\'t add the item to Wish List right now: %1.', $e->getMessage())
            );*/
        } catch (\Exception $e) {
            /*$this->messageManager->addExceptionMessage(
                $e,
                __('We can\'t add the item to Wish List right now.')
            );*/
        }
        $wishlistQty = $this->_objectManager->get(\Magento\Wishlist\Helper\Data::class)->getItemCount();

        $wishlistHelper = $this->_objectManager->get(\Magento\Wishlist\Helper\Data::class);
        $removeParam = $wishlistHelper->getRemoveParams($result);
        $msgArr = array(
            'success' => true,
            'product_id' => (int)$product->getId(),
            'wishlistQty' => $wishlistQty,
            'removeParam' => $removeParam
        );
        return $this->jsonResponse($msgArr);
        //$resultRedirect->setPath('*', ['wishlist_id' => $wishlist->getId()]);
        return $resultRedirect;
    }

    public function jsonResponse($response = ''){
        $jsonHelper = $this->_objectManager->get(\Magento\Framework\Json\Helper\Data::class);
        return $this->getResponse()->representJson($jsonHelper->jsonEncode($response));
    }
}

After that please add following code in your ajax success.

success: function(data){
    if(data.success == true){
         // You can add whatever you want to show success message.
         // I have added custom div class for an example
          $(".wishlist-success-message").css("display","block");
    }
}

Please try this and let me know if you have any question.

Second Option

Please use this extension for AJAX wishlist if you don't want to use your custom module : https://www.tigren.com/magento-2-extensions/ajax-suite-magento-2/

5
  • I'm not looking for a custom module solution. I just want to make an ajax call to 'add-to-wishlist' and get the response message. Is there any simpler solution than that? A pure js solution like the one I posted on description?
    – zekia
    Dec 11, 2018 at 13:35
  • this is simplest solution, because without any controller changes you can't get success response, you just need to override only one file to get success response Dec 12, 2018 at 4:02
  • Please check my updated ans Dec 12, 2018 at 4:45
  • Nice one do you have similar for remove from wishlist?
    – harri
    Jan 31, 2019 at 16:49
  • @AasimGoriya I couldn't override Magento\Wishlist\Controller\Index\Add, please correct me if I'm doing wrong: di.xml : <preference for="Magento\Wishlist\Controller\Index\Add" type="Vendor\Module\Controller\Wishlist\Index\Add" /> Controller: namespace Vendor\Module\Controller\Index; class Add extends \Magento\Wishlist\Controller\Wishlist\Index\Add {... Apr 16, 2019 at 5:37

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.