Question

My wishlist code:

<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/

/** @var Magento\Wishlist\Block\Catalog\Product\ProductList\Item\AddTo\Wishlist $block */
?>
<?php if ($block->getWishlistHelper()->isAllow()) : ?>


<a href="#"
class="action towishlist"
title="<?= $block->escapeHtmlAttr(__('Add to Wish List')) ?>"
aria-label="<?= $block->escapeHtmlAttr(__('Add to Wish List')) ?>"
data-post='<?= /* @noEscape */ $block->getAddToWishlistParams($block->getProduct()) ?>'
data-action="add-to-wishlist"
role="button">
<img class="whislist-icon product-id-<?php echo $block->getProduct()->getId();?>" src="<?php /* @escapeNotVerified */ echo $block->getViewFileUrl('images/whislist_icon.jpg'); ?>" />
<span><?= $block->escapeHtml(__('Add to Wish List')) ?></span>
</a>

<?php endif; ?>
<?php
$_objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$storeManager = $_objectManager->get('Magento\Store\Model\StoreManagerInterface');
$currentStore = $storeManager->getStore();
$mediaUrl = $currentStore->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_MEDIA);
$wishimage = $mediaUrl."after_added.jpg";
?>

<script>
require(['jquery'], function($){
jQuery.ajax({
url: '<?php echo $this->getUrl('addtowish/index/wishlist') ?>',
method: 'get',
dataType: 'json',
success: function(data) {
var wislistAddesCheckData = data;
var itemLenth = wislistAddesCheckData.items.length;
for(i=0;i<itemLenth; i++){
var wislistAddedProductId = wislistAddesCheckData.items[i].product_id;
$(".product-id-"+wislistAddedProductId).attr('src','<?php echo $wishimage ; ?>');
}
}
});
});
</script>

Now, if click wishlist icon its redirect to the wishlist landing page, how to stop that?

Was it helpful?

Solution

Please change code as per i have added here. Also modified it as per your need.

<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/

/** @var Magento\Wishlist\Block\Catalog\Product\ProductList\Item\AddTo\Wishlist $block */
?>
<?php if ($block->isWishListAllowed()) : ?>

    <a href="javascript:void(0);" class="action" id="custom-wishlist"
        title="<?= $block->escapeHtmlAttr(__('Add to Wish List')) ?>"
        aria-label="<?= $block->escapeHtmlAttr(__('Add to Wish List')) ?>" role="button">
        <img class="whislist-icon product-id-<?php echo $block->getProduct()->getId();?>" src="<?php /* @escapeNotVerified */ echo $block->getViewFileUrl('images/whislist_icon.jpg'); ?>" />
        <?php
            $_objectManager = \Magento\Framework\App\ObjectManager::getInstance();
            $storeManager = $_objectManager->get('Magento\Store\Model\StoreManagerInterface');
            $currentStore = $storeManager->getStore();
            $mediaUrl = $currentStore->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_MEDIA);
            $wishimage = $mediaUrl."after_added.jpg";
        ?>
        <img class="whislist-icon show-img-<?php echo $block->getProduct()->getId();?>" src="<?php /* @escapeNotVerified */ echo $wishimage; ?>" style="display:none;"/>
        <span><?= $block->escapeHtml(__('Add to Wish List')) ?></span>
    </a>

    <script>
    require(['jquery','Magento_Customer/js/customer-data'], function($,customerData){
        $( "#custom-wishlist" ).click(function() {
            jQuery.ajax({
                url: '<?php echo $this->getUrl('hideorders/index/wishlist') ?>',
                method: 'get',
                dataType: 'json',
                data: {
                    productId: "<?php echo $block->getProduct()->getId() ?>"
                },
                success: function(data) {
                    console.log(data.productid);
                    var productId = data.productid;
                    $(".product-id-"+productId).hide();
                    $(".show-img-"+productId).show();
                    //Do whatever you want to do
                    var sections = ['wishlist'];
                    customerData.invalidate(sections);
                    customerData.reload(sections, true);
                }
            });
        });
    });
    </script>
<?php endif; ?>

Please create controller file Wishlist.php file

<?php
/**
 *
 * Copyright © 2015 Zmagecommerce. All rights reserved.
 */
namespace PackageName\Module\Controller\Index;

use Magento\Framework\Controller\Result\JsonFactory;

class wishlist extends \Magento\Framework\App\Action\Action 
{
    protected $_customerSession;

    protected $_resultJsonFactory;

    protected $wishlistProvider;

    protected $_wishlistRepository;

    protected $_productRepository;

    public function __construct(
        \Magento\Framework\App\Action\Context $context,
        \Magento\Customer\Model\Session $customerSession,
        \Magento\Wishlist\Model\WishlistFactory $wishlistRepository,
        JsonFactory $resultJsonFactory,
        \Magento\Wishlist\Controller\WishlistProviderInterface $wishlistProvider,
        \Magento\Catalog\Api\ProductRepositoryInterface $productRepository
    ) {
        $this->_customerSession = $customerSession;
        $this->_wishlistRepository= $wishlistRepository;
        $this->_resultJsonFactory = $resultJsonFactory;
        $this->wishlistProvider = $wishlistProvider;
        $this->_productRepository = $productRepository;
        parent::__construct($context);
    }

    public function execute()
    {
        $response = [];
        $productId = $this->getRequest()->getParam('productId');
        $customerId = $this->_customerSession->getCustomer()->getId();
        if($productId && $customerId) {
            try {
                $product = $this->_productRepository->getById($productId);
            } catch (NoSuchEntityException $e) {
                $product = null;
            }

            if($product) {
                $wishlist = $this->_wishlistRepository->create()->loadByCustomerId($customerId, true);
                $wishlist->addNewItem($product);
                $wishlist->save();
                $response['productid'] = $productId; 
            }
        }

        $resultJson = $this->_resultJsonFactory->create();
        $resultJson->setData($response);
        return $resultJson;
    }
}

OTHER TIPS

I have checked your code. And you need to modify your code like below.

Because of "data-post" , it redirects.

data-post='<?= /* @noEscape */ $block->getAddToWishlistParams($block->getProduct()) ?>'  , this is passing data like below


{"action":"http:\/\/localhost\/magento2\/demo\/magento236\/wishlist\/index\/add\/","data":{"product":1,"uenc":"aHR0cDovL3NpdGVwcm9vZnMubmV0L21hZ2VudG8yL2Rod2FuaS9tYWdlbnRvMjM2L3Rlc3QtcHJvZHVjdC5odG1sP3F0eT00"}}

That's why it is redirects from above action. You have to remove "data-post" from your add to wishlist link and you have to pass data in your ajax call. Also you have to pass product id and other needed data in ajax call.

After that in your controller file , you have to load prodcut object by product id and add product in wishlist programmatically.

Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top