Redirect to customer account login page using Ajax – magento 2

Posted On: May 19, 2017

If you are trying to create a custom extension for adding product to wishlist using ajax. In this extension you want to check 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. Follow below code:-


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;



public function execute()    {

$response = [

‘errors’ => false,            ‘message’ => __(‘Item Added 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();


}        //Logic for customer login here



Also Read :   Building Backlinks willpower of Your Ecommerce Business
Subscribe to our newsletter
Subscribe to our newsletter today to receive updates on the latest news and offers.
100% Privacy. No spam guaranteed
webe tutorial