0

I created some module to login and register with Ajax, so I rewrite the :

  • vendor/magento/module-customer/Controller/Account/LoginPost.php
  • vendor/magento/module-customer/Controller/Account/CreatePost.php

Now I want to know how to return the string response from controller to Ajax without echo or return Json(...) to not breaks the controller for the non Ajax process !

To be more clear, the controller is used for the both, the native login and register process (non Ajax), and also in my new page with the Ajax. (as I said, I rewrite it), now I want to get the Magento errors cases like : $message = __('Incorrect username or password'); but I did not find a trick except an echo, this echo works but he breaks the non ajax process I mean instead to refresh the page then display a session message error, I will have my echo message : Incorrect username or password with an white page.

If someone knows how to return a data from controller to jQuery with Ajax without echo or return Json(new{...}) I am a taker otherwise Im obliged to clone the Magento_Custom module.

LoginPost.php controller

public function execute()
    {
        if ($this->session->isLoggedIn() || !$this->formKeyValidator->validate($this->getRequest())) {
            /** @var \Magento\Framework\Controller\Result\Redirect $resultRedirect */
            $resultRedirect = $this->resultRedirectFactory->create();
            $resultRedirect->setPath('*/*/');
            return $resultRedirect;
        }

        if ($this->getRequest()->isPost()) {
            $login = $this->getRequest()->getPost('login');
            if (!empty($login['username']) && !empty($login['password'])) {
                try {
                    $customer = $this->customerAccountManagement->authenticate($login['username'], $login['password']);
                    $this->session->setCustomerDataAsLoggedIn($customer);
                    $this->session->regenerateId();
                    if ($this->getCookieManager()->getCookie('mage-cache-sessid')) {
                        $metadata = $this->getCookieMetadataFactory()->createCookieMetadata();
                        $metadata->setPath('/');
                        $this->getCookieManager()->deleteCookie('mage-cache-sessid', $metadata);
                    }
                    echo 'ok'; /*for my condition ajax response to redirect to another page*/
                    //return $this->_redirect($this->_redirect->getRefererUrl());
                    $redirectUrl = $this->accountRedirect->getRedirectCookie();
                    if (!$this->getScopeConfig()->getValue('customer/startup/redirect_dashboard') && $redirectUrl) {
                        $this->accountRedirect->clearRedirectCookie();
                        $resultRedirect = $this->resultRedirectFactory->create();
                        // URL is checked to be internal in $this->_redirect->success()
                        //$resultRedirect->setUrl($this->_redirect->success($redirectUrl));
                        //return $resultRedirect;
                        return $this->_redirect($this->_redirect->getRefererUrl());
                    }
                } catch (EmailNotConfirmedException $e) {
                    $value = $this->customerUrl->getEmailConfirmationUrl($login['username']);
                    $message = __(
                        'This account is not confirmed. <a href="%1">Click here</a> to resend confirmation email.',
                        $value
                    );
                    $this->messageManager->addError($message);
                    echo $message.'&nbsp'.'<i class="fas fa-exclamation-circle"></i>';
                    $this->session->setUsername($login['username']);
                } catch (UserLockedException $e) {
                    $message = __(
                        'You did not sign in correctly or your account is temporarily disabled.'
                    );
                    $this->messageManager->addError($message);
                    echo $message.'&nbsp'.'<i class="fas fa-exclamation-circle"></i>';
                    $this->session->setUsername($login['username']);
                } catch (AuthenticationException $e) {
                    $message = __('Incorrect username or password');
                    $this->messageManager->addError($message);
                    echo $message.'&nbsp'.'<i class="fas fa-exclamation-circle"></i>';
                    $this->session->setUsername($login['username']);
                } catch (LocalizedException $e) {
                    $message = $e->getMessage();
                    $this->messageManager->addError($message);
                    echo $message.'&nbsp'.'<i class="fas fa-exclamation-circle"></i>';
                    $this->session->setUsername($login['username']);
                } catch (\Exception $e) {
                    // PA DSS violation: throwing or logging an exception here can disclose customer password
                    echo __('An unknown error occurred. Please contact us for help.');

                }
            } else {
                echo __('Email and password are required').'&nbsp'.'<i class="fas fa-exclamation-circle"></i>';
            }
        }
1

As I know, we shouldn't use "echo" in the controller. We should use an array to contain the values response and encode the array to JSON type.

We can check the request is Ajax or not: $this->getRequest()->isXmlHttpRequest(). We also can pass an Ajax parameter to url:\Magento\Framework\App\Request\Http::isAjax().

[Note] From my experience, we should't use a controller for both cases: Ajax and non Ajax controller. It's hard to read and control.

  • Thanks @Khoa TruongDinh for you answer, I think I will create a new controller for this one but there should be a trick anyway. – PЯINCƏ Apr 29 '18 at 21:12

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.