1

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.

  • Try after add die(); just after redirection code. – Prince Patel Aug 1 '17 at 10:23
  • @PrincePatel after add die(); function below $this->customerSession->authenticate(); its not call customer login url customer/account/login – Rajkumar .E Aug 1 '17 at 10:33
1

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.

0

As Per @Marius Answer, Finally achieved to redirect to customer login page, while ajax.

My Controller:

    <?php
    namespace Clorida\Greetings\Controller\Index;

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

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

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

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

                } else {
                    $response['redirectUrl'] = $this->_url->getUrl('customer/account/login');
                    $resultJson = $this->resultFactory->create(ResultFactory::TYPE_JSON);
                    $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);
              });
          }
      function execCommand(config) {
          $.ajax({
                  method: 'POST',
                  url: config.custom_image,
                  data: { q: 'some' },
                  dataType: "json",
                  showLoader: true
              })
              .done(function( msg ) {

                  console.log("getting response");

                if(msg.redirectUrl){

                    window.location.href = msg.redirectUrl;
                }
              });
      }
      return main;
  });

Clear Cache, Now Works Fine.

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.