Magento – Add product to wishlist using Ajax – get response message

ajaxmagento2magento2.2magento2.3.0wishlist

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?

Best Answer

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/