Magento 2 – Ajax Controller Not Redirecting to Login Page

ajaxcontrollersmagento-2.1magento2redirect

I have Custom Ajax Call, If Customer not login in, then redirected to Login page. But Controller call this code, its says redirected, its not redirected.

Reference:

enter image description here

My Code:

                <?php

      namespace Vendor\Module\Controller\Index;
      use Magento\Framework\Controller\Result\JsonFactory;

      class CustomImage extends \Magento\Framework\App\Action\Action
      {
          protected $logger;
          protected $_productRepositoryFactory;
          protected $_storeManager;
          protected $customerSession;
          protected $resultJsonFactory;


          public function __construct(
              \Magento\Framework\App\Action\Context $context,
              \Psr\Log\LoggerInterface $loggerinterface,
              \Magento\Customer\Model\Session $customerSession,
              \Magento\Catalog\Api\ProductRepositoryInterfaceFactory $productRepositoryFactory,
              JsonFactory $resultJsonFactory,
              \Magento\Store\Model\StoreManagerInterface $storeManager


          )
          {
              parent::__construct($context);
              $this->logger = $loggerinterface;
              $this->_productRepositoryFactory = $productRepositoryFactory;
              $this->_storeManager = $storeManager;
              $this->customerSession = $customerSession;
          }

          /**
           * Execute view action
           *
           * @return \Magento\Framework\Controller\ResultInterface
           */
          public function execute()
          {
              $this->logger->addDebug("Custom Image Block");
              try {

                  $this->logger->addDebug("try Block");
                  if ($this->customerSession->isLoggedIn()) {

                      //my code

                  } else {
                                    $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('customer/account/login');
                /** @var \Magento\Framework\Controller\Result\Json $resultJson */
                $resultJson = $this->resultJsonFactory->create();
                $resultJson->setData($response);
                return $resultJson;
            }
                  }

              } catch (Exception $e) {
                  $this->messageManager->addError($e->getMessage());
              }

          }
      }

My ajax.js

  define(["jquery"], function ($) {
      var main =
          function (config) {
              $("#finish_design_button").on("click", function () {
                  execCommand(config);
              });
          }
      //ajax request for load docker
      function execCommand(config) {
          $.ajax({
              url: config.custom_image,
              type: 'POST',
              showLoader: true,
              dataType: 'json'
          }).done(function (response) {
              console.log(response);

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

  });

My Template:

  <script type="text/x-magento-init">
      {
          "*": {
              "Vendor_Module/js/custom_image":{"custom_image":"<?php echo $block->getUrl('greeting/index/customimage', []); ?>"}
          }
      }
      </script>

Now,Thorw TypeError: response is null.

Suggest Me, whats Wrong in my code and how to get response from Controller.

Best Answer

The problem is your expectation. :).
This is how it works. You make an ajax call to a controller action. That one redirects to the customer login and sends the customer login page back. Then, the js function that handles the response from the ajax call should do something with the html for the login page. You are not telling the js callback to redirect to the login page.

You should make your controller action return a json and the js function that handles the response from the ajax call should interpret that JSON.
Instead of redirecting to the login you should send something back like {redirect:true}.
Then the js callback will check if response.redirect === true and redirect to the login page.

Related Topic