1

I have created a custom module for adding product to wishlist using ajax. In my custom module controller I have checked the user is login or not, if not logged in and trying to add to wishlist it won't redirect to customer account login page because of it appending the current module route id before it. How to resolve this issue?
Please solve this issue asap possible.

Add.php

<?php
namespace WeltPixel\Quickview\Controller\Index;
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;
use Magento\Framework\Controller\Result\JsonFactory;
class Add extends \Magento\Framework\App\Action\Action
{
    protected $_wishlistRepository;

    protected $_productRepository;
    //protected $customerSession;

    /**
     * @var JsonFactory
     */
    protected $resultJsonFactory;
    protected $response;

    // public function __construct(
    //     \Magento\Wishlist\Model\WishlistFactory $wishlistRepository,
    //     \Magento\Catalog\Api\ProductRepositoryInterface $productRepository
    // ) {
    //     $this->_wishlistRepository= $wishlistRepository;
    //     $this->_productRepository = $productRepository;
    // }
    public function __construct(
        //Session $customerSession,
        JsonFactory $resultJsonFactory,
        Action\Context $context,
        \Magento\Customer\Model\Session $customerSession,
        \Magento\Wishlist\Model\WishlistFactory $wishlistRepository,
        \Magento\Catalog\Api\ProductRepositoryInterface $productRepository,
        Validator $formKeyValidator
    ) {
        $this->resultJsonFactory = $resultJsonFactory;
         $this->customerSession = $customerSession;
         $this->_customerSession = $customerSession;
         $this->_wishlistRepository= $wishlistRepository;
         $this->_productRepository = $productRepository;
        $this->formKeyValidator = $formKeyValidator;
        parent::__construct($context);
    }
    public function execute()
    {  

      $productData = $this->getRequest()->getparam('product');

    $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
    $customerSession = $objectManager->get('Magento\Customer\Model\Session');
    if($customerSession->isLoggedIn()) {

        $customerId = $customerSession->getCustomer()->getId();
        //echo $customerId;die;
        $wishlist = $this->_wishlistRepository->create()->loadByCustomerId($customerId, true);

        $wishlist->addNewItem($productData);
        $wishlist->save();
        echo "success";
        return;

    }else{      
            //$response['errors'] = true;
            //$response['message'] = 'Error Here';
            //$this->_redirect('customer/account/login');
            //$response = $this->_url->getUrl('customer/account/login');            
            // return;
            /** @var \Magento\Framework\Controller\Result\Json $resultJson */
            //$resultJson = $this->resultJsonFactory->create();
            //  $resultJson->setData(['url'=>$response]);                         
            //  echo $response;
             // return $response;
  //           exit();
        // return $this->resultRedirectFactory->create()->setUrl(rm_request('customer/account/login/'));
        // echo "hiee";die;
        // $redirect = $objectManager->get('\Magento\Framework\App\Response\Http');
        // $redirect->setRedirect('../../customer/account/login/');
     //    return $redirect;
    }


    }
}

?>

customwishlist.phtml

<?php
$_objectManager = \Magento\Framework\App\ObjectManager::getInstance(); //instance of\Magento\Framework\App\ObjectManager
$storeManager = $_objectManager->get('Magento\Store\Model\StoreManagerInterface');
$currentStore = $storeManager->getStore();
$baseUrl = $currentStore->getBaseUrl();
$topCollection = $_objectManager->create('Magento\Catalog\Model\ResourceModel\Product\CollectionFactory');

$TopProductcollection = $topCollection->create()
        ->addAttributeToSelect('*')
        //->addAttributeToFilter('status', '1')
        //->addAttributeToFilter('is_in_stock',['eq' => 1])
        //->setOrder('position', 'DESC')
        //->setPageSize(6)
        //->setCurPage(1)
        ->load();

        foreach ($TopProductcollection as $collection) {
            $products = $collection->getData();
                //print_r($products);
                echo $products['entity_id'];
                ?>
                <a href="javascript:void(0)" onclick="ajaxWishUrl('<?php echo $products['entity_id'] ?>')">wishlist</a> <a href="javascript:void(0)" onclick="compareProductUrl('<?php echo $products['entity_id'] ?>')"> compare</a>

      <?php   }


$FormKey = $_objectManager->get('Magento\Framework\Data\Form\FormKey');
?>
<!--  <span id="cartLoader" style="display:none"><img src="<?php echo $baseUrl; ?>ajax-loader.gif"  width="30" height="30"></span> -->
<script type="text/javascript">    


/*Top Selling Compare*/ 
    function compareProductUrl(id) {
        //jQuery("#cartLoader").fadeIn();
        var form_key = '<?php echo $FormKey->getFormKey(); ?>';
        jQuery.ajax({
            type: "POST",
            dataType: 'json',
            data: 'product=' + id + '&form_key=' + form_key,
            url: "<?php echo $baseUrl; ?>catalog/product_compare/add",
            success: function(data) {
               // jQuery("#cartLoader").fadeOut();
            }
        });
    }

/*Top Selling Wishlist*/

    function ajaxWishUrl(id) {
        ///jQuery("#cartLoader").fadeIn();
        var form_key = '<?php echo $FormKey->getFormKey(); ?>';
        jQuery.ajax({
            type: "POST",
            dataType: 'json',
            data: 'product=' + id + '&form_key=' + form_key,
            url: "<?php echo $baseUrl; ?>weltpixel_quickview/index/add",
            success: function(data) {
                alert(data);
        //              if (data.redirectUrl) {
        //                 window.location.href = response.redirectUrl;
        //             }
        // alert("succc");
                //jQuery("#cartLoader1").fadeOut();
            }
        });
    }


</script>
  • Can you provide your code please. – Ben Crook May 17 '17 at 14:31
  • Your question is not clear to me, however, I try to answer your question in general way. – Khoa TruongDinh May 17 '17 at 14:56
  • yeah i have update my code – Mandar Parbate May 18 '17 at 5:18
  • please check if there any wrong? – Mandar Parbate May 18 '17 at 5:19
  • and please check the else session of execute function – Mandar Parbate May 18 '17 at 5:19
1

We can set the redirect url in our ajax response.

For example:

<?php

namespace Vendor\Customer\Controller\Ajax;

use Magento\Framework\App\Action\Context;
use Magento\Customer\Model\Session;
use Magento\Framework\Controller\Result\JsonFactory;
use Magento\Framework\App\Action\Action;

class Wishlist extends Action
{
    /**
     * @var Session
     */
    protected $customerSession;

    /**
     * @var JsonFactory
     */
    protected $resultJsonFactory;

    /**
     * Wishlist constructor.
     * @param Session $customerSession
     * @param JsonFactory $resultJsonFactory
     * @param Context $context
     */
    public function __construct(
        Session $customerSession,
        JsonFactory $resultJsonFactory,
        Context $context
    )
    {
        $this->customerSession = $customerSession;
        parent::__construct($context);
    }

    public function execute()
    {
        $response = [
            'errors' => false,
            'message' => __('Added Item successful.')
        ];
        //If not not login and check isXml Http request(Ajax)
        if(!$this->customerSession->isLoggedIn() && !$this->getRequest()->isXmlHttpRequest()) {
            $response['errors'] = true;
            $response['message'] = 'Error Here';
            $response['redirectUrl'] = $this->_url->getUrl('controller/you/want');
            /** @var \Magento\Framework\Controller\Result\Json $resultJson */
            $resultJson = $this->resultJsonFactory->create();
            $resultJson->setData($response);

        }
        //Logic for customer login here
    }
}

In our Ajax function, we need to check the return url

 if (response.redirectUrl) {
         window.location.href = response.redirectUrl;
 }

We can see more:

  • vendor/magento/module-customer/Controller/Ajax/Login.php
  • vendor/magento/module-customer/view/frontend/web/js/action/login.js

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.