Custom Customer Ajax Login Extension in Magento 2

In this article, we are going to develop a Magento 2 custom customer ajax login extension which will be something like adding a customer ajax popup in login and registration through the module in Magento 2.

 

Add Ajax PopUp Login And Registration

Now through this module, we will add an ajax popup in login and registration in Magento 2 so for that we need to create a module so in order to create that module we have to create the following files.

app/code/Wishusucess/CustomerAccount/registration.php

app/code/Wishusucess/CustomerAccount/etc/module.xml

app/code/Wishusucess/CustomerAccount/etc/frontend/sections.xml

app/code/Wishusucess/CustomerAccount/etc/frontend/routes.xml

app/code/Wishusucess/CustomerAccount/Controller/Customer/Ajax/Register.php

app/code/Wishusucess/CustomerAccount/Block/Form/Login.php

app/code/Wishusucess/CustomerAccount/Block/Form/Register.php

app/code/Wishusucess/CustomerAccount/view/frontend/layout/default.xml

app/code/Wishusucess/CustomerAccount/view/frontend/templates/login.phtml

app/code/Wishusucess/CustomerAccount/view/frontend/templates/register.phtml

app/code/Wishusucess/CustomerAccount/view/frontend/web/js/action/customer-authentication-popup.js

 

Magento 2 Add-in PopUp Customer Register

Create Customer Login PopUp

Magento 2 Customer PopUp Login

Custom Customer Ajax Login

Registration Customer Account PopUp Login

app/code/Wishusucess/CustomerAccount/registration.php

<?php
/**
* Source Wishusucess
* package Wishusucess_CustomerAccount
* Author Wishusucess Magento Development Team
* website https://www.wishusucess.com/
*/
\Magento\Framework\Component\ComponentRegistrar::register(
\Magento\Framework\Component\ComponentRegistrar::MODULE,
'Wishusucess_CustomerAccount',
__DIR__
);

 

Declare Module information of Customer Account

app/code/Wishusucess/CustomerAccount/etc/module.xml

<?xml version="1.0"?>
<!--
/**
* Source Wishusucess
* package Wishusucess_CustomerAccount
* Author Wishusucess Magento Development Team
* website https://www.wishusucess.com/
*/
-->
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
<module name="Wishusucess_CustomerAccount" setup_version="2.1.0" />
</config>

 

Create Section XML File For Custom Customer Ajax Login

This section XML file is a kind of customer data that is grouped together. So here that each section of customer data will have a key or that will be represented by a key that helps to access the content of customer data.

app/code/Wishusucess/CustomerAccount/etc/frontend/sections.xml

<?xml version="1.0"?>
<!--
/**
* Source Wishusucess
* package Wishusucess_CustomerAccount
* Author Wishusucess Magento Development Team
* website https://www.wishusucess.com/
*/
-->
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Customer:etc/sections.xsd">
<action name="wishusucess/customer_ajax/register">
<section name="checkout-data"/>
<section name="cart"/>
<section name="customer"/>
</action>
<action name="customer/ajax/login">
<section name="checkout-data"/>
<section name="cart"/>
<section name="customer"/>
</action>
</config>

 

Routes XML File For Customer Account in Magento 2

app/code/Wishusucess/CustomerAccount/etc/frontend/routes.xml

<?xml version="1.0"?>
<!--
/**
* Source Wishusucess
* package Wishusucess_CustomerAccount
* Author Wishusucess Magento Development Team
* website https://www.wishusucess.com/
*/
-->
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:App/etc/routes.xsd">
<router id="standard">
<route id="wishusucess" frontName="wishusucess">
<module name="Wishusucess_CustomerAccount"/>
</route>
</router>
</config>

 

Custom Customer Ajax Login Register

This code will add Magento 2 PopUp Registration in your customer registration section.

app/code/Wishusucess/CustomerAccount/Controller/Customer/Ajax/Register.php

<?php
/**
* Source Wishusucess
* package Wishusucess_CustomerAccount
* Author Wishusucess Magento Development Team
* website https://www.wishusucess.com/
*/
namespace Wishusucess\CustomerAccount\Controller\Customer\Ajax;

use Magento\Framework\Exception\StateException;
use Magento\Framework\Exception\InputException;
use Magento\Framework\Exception\LocalizedException;
use Magento\Customer\Helper\Address;
use Magento\Customer\Model\Account\Redirect;
use Magento\Framework\App\ObjectManager;
use Magento\Customer\Api\AccountManagementInterface;

class Register extends \Magento\Framework\App\Action\Action
{
/**
* @var \Magento\Framework\Controller\Result\JsonFactory
*/
protected $resultJsonFactory;

/**
* @var \Magento\Framework\Controller\Result\RawFactory
*/
protected $resultRawFactory;

/**
* @var \Magento\Customer\Model\Session
*/
protected $session;

/**
* @var \Magento\Customer\Model\Registration
*/
protected $registration;

/**
* @var \Magento\Framework\Data\Form\FormKey\Validator
*/
protected $formKeyValidator;

/**
* @var \Magento\Customer\Model\CustomerExtractor
*/
protected $customerExtractor;

/**
* @var \Magento\Customer\Api\AccountManagementInterface
*/
protected $accountManagement;

/**
* @var \Magento\Newsletter\Model\SubscriberFactory
*/
protected $subscriberFactory;

/**
* @var \Magento\Customer\Model\Url
*/
protected $customerUrl;

/**
* @var \Magento\Customer\Helper\Address
*/
protected $addressHelper;

/**
* @var \Magento\Store\Model\StoreManagerInterface
*/
protected $storeManager;

/**
* @var \Magento\Customer\Model\Account\Redirect
*/
protected $accountRedirect;

/**
* @var \Magento\Framework\App\Config\ScopeConfigInterface
*/
protected $scopeConfig;

/**
* @var \Magento\Framework\Stdlib\Cookie\CookieMetadataFactory
*/
protected $cookieMetadataFactory;

/**
* @var \Magento\Framework\Stdlib\Cookie\PhpCookieManager
*/
protected $cookieMetadataManager;

/**
* @var \Magento\Framework\Escaper
*/
protected $escaper;

/**
* @param \Magento\Framework\App\Action\Context $context
* @param \Magento\Framework\Controller\Result\JsonFactory $resultJsonFactory
* @param \Magento\Framework\Controller\Result\RawFactory $resultRawFactory
* @param \Magento\Customer\Model\Session $customerSession
* @param \Magento\Customer\Model\Registration $customerRegistration
* @param \Magento\Framework\Data\Form\FormKey\Validator $formKeyValidator
* @param \Magento\Customer\Api\AccountManagementInterface $accountManagement
* @param \Magento\Customer\Model\CustomerExtractor $customerExtractor
* @param \Magento\Newsletter\Model\SubscriberFactory $subscriberFactory
* @param \Magento\Customer\Model\Url $customerUrl
* @param \Magento\Framework\UrlInterface $urlModel
* @param \Magento\Customer\Helper\Address $addressHelper
* @param \Magento\Store\Model\StoreManagerInterface $storeManager
* @param \Magento\Customer\Model\Account\Redirect $accountRedirect
* @param \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig
* @param \Magento\Framework\Escaper $escaper
* @param \Magento\Framework\Stdlib\Cookie\CookieMetadataFactory $cookieMetadataFactory
* @param \Magento\Framework\Stdlib\Cookie\PhpCookieManager $cookieMetadataManager
*/
public function __construct(
\Magento\Framework\App\Action\Context $context,
\Magento\Framework\Controller\Result\JsonFactory $resultJsonFactory,
\Magento\Framework\Controller\Result\RawFactory $resultRawFactory,
\Magento\Customer\Model\Session $customerSession,
\Magento\Customer\Model\Registration $customerRegistration,
\Magento\Framework\Data\Form\FormKey\Validator $formKeyValidator,
\Magento\Customer\Api\AccountManagementInterface $accountManagement,
\Magento\Customer\Model\CustomerExtractor $customerExtractor,
\Magento\Newsletter\Model\SubscriberFactory $subscriberFactory,
\Magento\Customer\Model\Url $customerUrl,
\Magento\Framework\UrlInterface $urlModel,
\Magento\Customer\Helper\Address $addressHelper,
\Magento\Store\Model\StoreManagerInterface $storeManager,
\Magento\Customer\Model\Account\Redirect $accountRedirect,
\Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig,
\Magento\Framework\Escaper $escaper,
\Magento\Framework\Stdlib\Cookie\CookieMetadataFactory $cookieMetadataFactory,
\Magento\Framework\Stdlib\Cookie\PhpCookieManager $cookieMetadataManager
) {
parent::__construct($context);
$this->resultJsonFactory = $resultJsonFactory;
$this->resultRawFactory = $resultRawFactory;
$this->session = $customerSession;
$this->registration = $customerRegistration;
$this->formKeyValidator = $formKeyValidator;
$this->accountManagement = $accountManagement;
$this->customerExtractor = $customerExtractor;
$this->subscriberFactory = $subscriberFactory;
$this->customerUrl = $customerUrl;
$this->urlModel = $urlModel;
$this->addressHelper = $addressHelper;
$this->storeManager = $storeManager;
$this->accountRedirect = $accountRedirect;
$this->scopeConfig = $scopeConfig;
$this->escaper = $escaper;
}

/**
* Retrieve cookie manager
*
* @deprecated 100.1.0
* @return \Magento\Framework\Stdlib\Cookie\PhpCookieManager
*/
private function getCookieManager()
{
if (!$this->cookieMetadataManager) {
$this->cookieMetadataManager = ObjectManager::getInstance()->get(
\Magento\Framework\Stdlib\Cookie\PhpCookieManager::class
);
}
return $this->cookieMetadataManager;
}

/**
* Retrieve cookie metadata factory
*
* @deprecated 100.1.0
* @return \Magento\Framework\Stdlib\Cookie\CookieMetadataFactory
*/
private function getCookieMetadataFactory()
{
if (!$this->cookieMetadataFactory) {
$this->cookieMetadataFactory = ObjectManager::getInstance()->get(
\Magento\Framework\Stdlib\Cookie\CookieMetadataFactory::class
);
}
return $this->cookieMetadataFactory;
}

/**
* @return \Magento\Framework\Controller\ResultInterface
* @SuppressWarnings(PHPMD.CyclomaticComplexity)
*/
public function execute()
{
$credentials = null;
$httpBadRequestCode = 400;

/** @var \Magento\Framework\Controller\Result\Raw $resultRaw */
$resultRaw = $this->resultRawFactory->create();
if ($this->getRequest()->getMethod() !== 'POST' || !$this->getRequest()->isXmlHttpRequest()) {
return $resultRaw->setHttpResponseCode($httpBadRequestCode);
}

$formKeyValidation = $this->formKeyValidator->validate($this->getRequest());

$response = [
'errors' => false,
'message' => __('Login successful.')
];

if ($this->session->isLoggedIn()) {
$response = [
'errors' => false,
'message' => __('You are already logged in.')
];
} elseif (!$this->registration->isAllowed()) {
$response = [
'errors' => true,
'message' => __('Customer registration is already disabled.')
];
} elseif (!$formKeyValidation) {
$response = [
'errors' => true,
'message' => $this->getRequest()->getParam('password')
];
} else {
$this->session->regenerateId();
try {
$customer = $this->customerExtractor->extract('customer_account_create', $this->_request);

$password = $this->getRequest()->getParam('password');
$confirmation = $this->getRequest()->getParam('password_confirmation');

$this->checkPasswordConfirmation($password, $confirmation);

$customer = $this->accountManagement
->createAccount($customer, $password);

if ($this->getRequest()->getParam('is_subscribed', false)) {
$this->subscriberFactory->create()->subscribeCustomerById($customer->getId());
}

$this->_eventManager->dispatch(
'customer_register_success',
['account_controller' => $this, 'customer' => $customer]
);

$confirmationStatus = $this->accountManagement->getConfirmationStatus($customer->getId());
if ($confirmationStatus === AccountManagementInterface::ACCOUNT_CONFIRMATION_REQUIRED) {
$email = $this->customerUrl->getEmailConfirmationUrl($customer->getEmail());
$response = [
'errors' => true,
'message' => __(
'You must confirm your account. Please check your email for the confirmation link or <a href="%1">click here</a> for a new link.',
$email
)
];
} else {
$this->session->setCustomerDataAsLoggedIn($customer);
$response = [
'errors' => false,
'message' => $this->getSuccessMessage()
];
$requestedRedirect = $this->accountRedirect->getRedirectCookie();
if (!$this->scopeConfig->getValue('customer/startup/redirect_dashboard') && $requestedRedirect) {
$response['redirectUrl'] = $this->_redirect->success($requestedRedirect);
$this->accountRedirect->clearRedirectCookie();
}
}
if ($this->getCookieManager()->getCookie('mage-cache-sessid')) {
$metadata = $this->getCookieMetadataFactory()->createCookieMetadata();
$metadata->setPath('/');
$this->getCookieManager()->deleteCookie('mage-cache-sessid', $metadata);
}
} catch (StateException $e) {
$url = $this->_url->getUrl('customer/account/forgotpassword');
$response = [
'errors' => true,
'message' => __(
'There is already an account with this email address. If you are sure that it is your email address, <a href="%1">click here</a> to get your password and access your account.',
$url
)
];
} catch (InputException $e) {
$response = [
'errors' => true,
'message' => $this->escaper->escapeHtml($e->getMessage())
];
} catch (LocalizedException $e) {
$response = [
'errors' => true,
'message' => $this->escaper->escapeHtml($e->getMessage())
];
} catch (\Exception $e) {
$response = [
'errors' => true,
'message' => __('We can\'t save the customer.')
];
}

$this->session->setCustomerFormData($this->getRequest()->getPostValue());
}

/** @var \Magento\Framework\Controller\Result\Json $resultJson */
$resultJson = $this->resultJsonFactory->create();
return $resultJson->setData($response);
}

/**
* Make sure that password and password confirmation matched
*
* @param string $password
* @param string $confirmation
* @return void
* @throws InputException
*/
protected function checkPasswordConfirmation($password, $confirmation)
{
if ($password != $confirmation) {
throw new InputException(__('Please make sure your passwords match.'));
}
}

/**
* Retrieve success message
*
* @return string
*/
protected function getSuccessMessage()
{
if ($this->addressHelper->isVatValidationEnabled()) {
if ($this->addressHelper->getTaxCalculationAddressType() == Address::TYPE_SHIPPING) {
// @codingStandardsIgnoreStart
$message = __(
'If you are a registered VAT customer, please <a href="%1">click here</a> to enter your shipping address for proper VAT calculation.',
$this->_url->getUrl('customer/address/edit')
);
// @codingStandardsIgnoreEnd
} else {
// @codingStandardsIgnoreStart
$message = __(
'If you are a registered VAT customer, please <a href="%1">click here</a> to enter your billing address for proper VAT calculation.',
$this->_url->getUrl('customer/address/edit')
);
// @codingStandardsIgnoreEnd
}
} else {
$message = __('Thank you for registering with %1.', $this->storeManager->getStore()->getFrontendName());
}
return $message;
}
}

 

Magento 2 Ajax Login PopUp

So here we can add Magento 2 ajax login through this code. When we will click on the customer login then there will be one popup open for the customer login.

app/code/Wishusucess/CustomerAccount/Block/Form/Login.php

<?php
/**
* Source Wishusucess
* package Wishusucess_CustomerAccount
* Author Wishusucess Magento Development Team
* website https://www.wishusucess.com/
*/
namespace Wishusucess\CustomerAccount\Block\Form;

class Login extends \Magento\Framework\View\Element\Template
{
/**
* @var \Magento\Customer\Model\Session
*/
protected $customerSession;

/**
* @var \Magento\Framework\App\Http\Context
*/
protected $httpContext;

/**
* Registration
*
* @var \Magento\Customer\Model\Registration
*/
protected $registration;

/**
* @param \Magento\Framework\View\Element\Template\Context $context
* @param \Magento\Customer\Model\Session $customerSession
* @param \Magento\Framework\App\Http\Context $httpContext
* @param \Magento\Customer\Model\Registration $registration
* @param array $data
*/
public function __construct(
\Magento\Framework\View\Element\Template\Context $context,
\Magento\Customer\Model\Session $customerSession,
\Magento\Framework\App\Http\Context $httpContext,
\Magento\Customer\Model\Registration $registration,
array $data = []
) {
parent::__construct($context, $data);
$this->customerSession = $customerSession;
$this->httpContext = $httpContext;
$this->registration = $registration;
}

/**
* Return registration
*
* @return \Magento\Customer\Model\Registration
*/
public function getRegistration()
{
return $this->registration;
}

/**
* Retrieve form posting url
*
* @return string
*/
public function getPostActionUrl()
{
return $this->getUrl('customer/ajax/login');
}

/**
* Check if autocomplete is disabled on storefront
*
* @return bool
*/
public function isAutocompleteDisabled()
{
return (bool)!$this->_scopeConfig->getValue(
\Magento\Customer\Model\Form::XML_PATH_ENABLE_AUTOCOMPLETE,
\Magento\Store\Model\ScopeInterface::SCOPE_STORE
);
}

/**
* Checking customer login status
*
* @return bool
*/
public function customerIsAlreadyLoggedIn()
{
return (bool)$this->httpContext->getValue(\Magento\Customer\Model\Context::CONTEXT_AUTH);
}

/**
* Retrieve registering URL
*
* @return string
*/
public function getCustomerRegistrationUrl()
{
return $this->getUrl('customer/account/create');
}
}

 

Create Block For Ajax Register

in order to create a Magento2 custom customer ajax login we have to create a block for the customer registration.

app/code/Wishusucess/CustomerAccount/Block/Form/Register.php

<?php
/**
* Source Wishusucess
* package Wishusucess_CustomerAccount
* Author Wishusucess Magento Development Team
* website https://www.wishusucess.com/
*/
namespace Wishusucess\CustomerAccount\Block\Form;

use Magento\Customer\Model\AccountManagement;

class Register extends \Magento\Directory\Block\Data
{
/**
* @var \Magento\Customer\Model\Session
*/
protected $customerSession;

/**
* @var \Magento\Framework\Module\Manager
*/
protected $moduleManager;

/**
* @var \Magento\Framework\App\Http\Context
*/
protected $httpContext;

/**
* Registration
*
* @var \Magento\Customer\Model\Registration
*/
protected $registration;

/**
* Constructor
*
* @param \Magento\Framework\View\Element\Template\Context $context
* @param \Magento\Directory\Helper\Data $directoryHelper
* @param \Magento\Framework\Json\EncoderInterface $jsonEncoder
* @param \Magento\Framework\App\Cache\Type\Config $configCacheType
* @param \Magento\Directory\Model\ResourceModel\Region\CollectionFactory $regionCollectionFactory
* @param \Magento\Directory\Model\ResourceModel\Country\CollectionFactory $countryCollectionFactory
* @param \Magento\Framework\Module\Manager $moduleManager
* @param \Magento\Customer\Model\Session $customerSession
* @param \Magento\Framework\App\Http\Context $httpContext
* @param \Magento\Customer\Model\Registration $registration
* @param array $data
*
* @SuppressWarnings(PHPMD.ExcessiveParameterList)
*/
public function __construct(
\Magento\Framework\View\Element\Template\Context $context,
\Magento\Directory\Helper\Data $directoryHelper,
\Magento\Framework\Json\EncoderInterface $jsonEncoder,
\Magento\Framework\App\Cache\Type\Config $configCacheType,
\Magento\Directory\Model\ResourceModel\Region\CollectionFactory $regionCollectionFactory,
\Magento\Directory\Model\ResourceModel\Country\CollectionFactory $countryCollectionFactory,
\Magento\Framework\Module\Manager $moduleManager,
\Magento\Customer\Model\Session $customerSession,
\Magento\Customer\Model\Url $customerUrl,
\Magento\Framework\App\Http\Context $httpContext,
\Magento\Customer\Model\Registration $registration,
array $data = []
) {
$this->moduleManager = $moduleManager;
$this->customerSession = $customerSession;
$this->httpContext = $httpContext;
$this->registration = $registration;
parent::__construct(
$context,
$directoryHelper,
$jsonEncoder,
$configCacheType,
$regionCollectionFactory,
$countryCollectionFactory,
$data
);
}

/**
* Return registration
*
* @return \Magento\Customer\Model\Registration
*/
public function getRegistration()
{
return $this->registration;
}

/**
* Retrieve the form posting URL
*
* @return string
*/
public function getPostActionUrl()
{
return $this->getUrl('wishusucess/customer_ajax/register');
}

/**
* Retrieve back URL
*
* @return string
*/
public function getBackUrl()
{
return $this->getUrl('customer/account/login');
}

/**
* Retrieve form data
*
* @return mixed
*/
public function getFormData()
{
$data = $this->getData('form_data');
if ($data === null) {
$formData = $this->customerSession->getCustomerFormData(true);
$data = new \Magento\Framework\DataObject();
if ($formData) {
$data->addData($formData);
$data->setCustomerData(1);
}
if (isset($data['region_id'])) {
$data['region_id'] = (int)$data['region_id'];
}
$this->setData('form_data', $data);
}
return $data;
}

/**
* Newsletter module availability
*
* @return bool
*/
public function isNewsletterEnabled()
{
return $this->moduleManager->isOutputEnabled('Magento_Newsletter');
}

/**
* Get minimum password length
*
* @return string
*/
public function getMinimumPasswordLength()
{
return $this->_scopeConfig->getValue(AccountManagement::XML_PATH_MINIMUM_PASSWORD_LENGTH);
}

/**
* Get number of password required character classes
*
* @return string
*/
public function getRequiredCharacterClassesNumber()
{
return $this->_scopeConfig->getValue(AccountManagement::XML_PATH_REQUIRED_CHARACTER_CLASSES_NUMBER);
}

/**
* Checking customer login status
*
* @return bool
*/
public function customerIsAlreadyLoggedIn()
{
return (bool)$this->httpContext->getValue(\Magento\Customer\Model\Context::CONTEXT_AUTH);
}
}

 

Now Call Template in XML File

app/code/Wishusucess/CustomerAccount/view/frontend/layout/default.xml

<?xml version="1.0"?>
<!--
/**
* Source Wishusucess
* package Wishusucess_CustomerAccount
* Author Wishusucess Magento Development Team
* website https://www.wishusucess.com/
*/
-->
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
<body>
<referenceBlock name="register-link">
<arguments>
<argument name="class" xsi:type="string">customer-register-link</argument>
</arguments>
</referenceBlock>
<referenceBlock name="authorization-link-login">
<arguments>
<argument name="class" xsi:type="string">customer-login-link</argument>
</arguments>
</referenceBlock>
<referenceContainer name="before.body.end">
<block class="Wishusucess\CustomerAccount\Block\Form\Login" name="customer-popup-login" template="Wishusucess_CustomerAccount::login.phtml" />
<block class="Wishusucess\CustomerAccount\Block\Form\Register" name="customer-popup-register" template="Wishusucess_CustomerAccount::register.phtml" />
</referenceContainer>
</body>
</page>

 

Create Custom Customer Ajax Login View

app/code/Wishusucess/CustomerAccount/view/frontend/templates/login.phtml

<?php
/**
* Source Wishusucess
* package Wishusucess_CustomerAccount
* Author Wishusucess Magento Development Team
* website https://www.wishusucess.com/
*/
/** @var \Wishusucess\CustomerAccount\Block\Form\Login $block */
?>
<?php if (!$block->customerIsAlreadyLoggedIn()): ?>
<style>
.customer-popup-login {
display: none;
}
.or-another-selection {
display: inline-block;
padding-right: 5px;
}
@media(max-width: 767px) {
.or-another-selection {
display: block;
text-align: center;
margin-bottom: 5px;
}
}
</style>
<div id="customer-popup-login" class="customer-popup-login">
<div class="block block-customer-login">
<div class="block-content" aria-labelledby="block-customer-popup-login-heading">
<form class="form form-login"
action="<?php /* @escapeNotVerified */ echo $block->getPostActionUrl() ?>"
method="post"
id="customer-popup-login-form"
data-mage-init='{"validation":{}}'>
<?php echo $block->getBlockHtml('formkey'); ?>
<input type="hidden" name="redirect_url" value="<?php echo $this->getUrl('*/*/*', ['_current' => true, '_use_rewrite' => true]); ?>" />
<fieldset class="fieldset login" data-hasrequired="<?php /* @escapeNotVerified */ echo __('* Required Fields') ?>">
<div class="field note"><?php /* @escapeNotVerified */ echo __('If you have an account, sign in with your email address.') ?></div>
<div class="messages"></div>
<div class="field email required">
<label class="label" for="email"><span><?php /* @escapeNotVerified */ echo __('Email') ?></span></label>
<div class="control">
<input name="username" value="" <?php if ($block->isAutocompleteDisabled()) :?> autocomplete="off"<?php endif; ?> id="email-login" type="email" class="input-text" title="<?php /* @escapeNotVerified */ echo __('Email') ?>" data-validate="{required:true, 'validate-email':true}">
</div>
</div>
<div class="field password required">
<label for="pass" class="label"><span><?php /* @escapeNotVerified */ echo __('Password') ?></span></label>
<div class="control">
<input name="password" type="password" <?php if ($block->isAutocompleteDisabled()) :?> autocomplete="off"<?php endif; ?> class="input-text" id="pass-login" title="<?php /* @escapeNotVerified */ echo __('Password') ?>" data-validate="{required:true}" >
</div>
</div>
<div class="actions-toolbar">
<div class="primary"><button type="submit" class="action login primary" name="send" id="send2-login"><span><?php /* @escapeNotVerified */ echo __('Sign In') ?></span></button></div>
<?php if ($block->getRegistration()->isAllowed()): ?>
<div class="or-another-selection"><?php echo __('or'); ?></div>
<div class="secondary"><a class="action remind" href="<?php /* @escapeNotVerified */ echo $block->getCustomerRegistrationUrl() ?>" id="customer-popup-registration"><span><?php /* @escapeNotVerified */ echo __('Create an Account') ?></span></a></div>
<?php endif; ?>
</div>
</fieldset>
</form>
</div>
</div>
<script type="text/x-magento-init">
{
"#customer-popup-login": {
"Wishusucess_CustomerAccount/js/action/customer-authentication-popup": {
"popupTitle": "<?php /* @escapeNotVerified */ echo __('Sign In') ?>",
"innerWidth": "400"
}
}
}
</script>
</div>
<?php endif; ?>

 

Create Custom Customer Ajax Register View

app/code/Wishusucess/CustomerAccount/view/frontend/templates/register.phtml

<?php
/**
* Source Wishusucess
* package Wishusucess_CustomerAccount
* Author Wishusucess Magento Development Team
* website https://www.wishusucess.com/
*/
/** @var \Wishusucess\CustomerAccount\Block\Form\Register $block */
?>
<?php if (!$block->customerIsAlreadyLoggedIn() && $block->getRegistration()->isAllowed()): ?>
<style>
.customer-popup-register {
display: none;
}
</style>
<div id="customer-popup-register" class="customer-popup-register">
<form class="form-create-account" action="<?php /* @escapeNotVerified */ echo $block->getPostActionUrl() ?>" method="post" id="customer-popup-form-register" enctype="multipart/form-data" autocomplete="off" data-mage-init='{"validation":{}}'>
<?php echo $block->getBlockHtml('formkey'); ?>
<input type="hidden" name="redirect_url" value="<?php echo $this->getUrl('*/*/*', ['_current' => true, '_use_rewrite' => true]); ?>" />
<div class="messages"></div>
<p><?php /* @escapeNotVerified */ echo __('Creating an account has many benefits: check out faster, keep more than one address, track orders and more.') ?></p>
<fieldset class="fieldset create info">
<legend class="legend"><span><?php /* @escapeNotVerified */ echo __('Personal Information') ?></span></legend><br>
<?php echo $block->getLayout()->createBlock('Magento\Customer\Block\Widget\Name')->setObject($block->getFormData())->setForceUseCustomerAttributes(true)->toHtml() ?>
<?php if ($block->isNewsletterEnabled()): ?>
<div class="field choice newsletter">
<input type="checkbox" name="is_subscribed" title="<?php /* @escapeNotVerified */ echo __('Sign Up for Newsletter') ?>" value="1" id="popup-is_subscribed" class="checkbox">
<label for="is_subscribed" class="label"><span><?php /* @escapeNotVerified */ echo __('Sign Up for Newsletter') ?></span></label>
</div>
<?php endif ?>
</fieldset>
<fieldset class="fieldset create account" data-hasrequired="<?php /* @escapeNotVerified */ echo __('* Required Fields') ?>">
<legend class="legend"><span><?php /* @escapeNotVerified */ echo __('Sign-in Information') ?></span></legend><br>
<div class="field required">
<label for="popup-email_address" class="label"><span><?php /* @escapeNotVerified */ echo __('Email') ?></span></label>
<div class="control">
<input type="email" name="email" autocomplete="email" id="popup-email_address" value="" title="<?php /* @escapeNotVerified */ echo __('Email') ?>" class="input-text" data-validate="{required:true, 'validate-email':true}">
</div>
</div>
<div class="field password required" data-mage-init='{"passwordStrengthIndicator": {}}'>
<label for="password" class="label"><span><?php /* @escapeNotVerified */ echo __('Password') ?></span></label>
<div class="control">
<input type="password" name="password" id="password"
title="<?php /* @escapeNotVerified */ echo __('Password') ?>"
class="input-text"
data-password-min-length="<?php echo $block->escapeHtml($block->getMinimumPasswordLength()) ?>"
data-password-min-character-sets="<?php echo $block->escapeHtml($block->getRequiredCharacterClassesNumber()) ?>"
data-validate="{required:true, 'validate-customer-password':true}"
autocomplete="off">
<div id="password-strength-meter-container" data-role="password-strength-meter" >
<div id="password-strength-meter" class="password-strength-meter">
<?php /* @escapeNotVerified */ echo __('Password Strength'); ?>:
<span id="password-strength-meter-label" data-role="password-strength-meter-label" >
<?php /* @escapeNotVerified */ echo __('No Password'); ?>
</span>
</div>
</div>
</div>
</div>
<div class="field confirmation required">
<label for="password-confirmation" class="label"><span><?php /* @escapeNotVerified */ echo __('Confirm Password') ?></span></label>
<div class="control">
<input type="password" name="password_confirmation" title="<?php /* @escapeNotVerified */ echo __('Confirm Password') ?>" id="password-confirmation" class="input-text" data-validate="{required:true, equalTo:'#password'}" autocomplete="off">
</div>
</div>
</fieldset>
<div class="actions-toolbar">
<div class="primary">
<button type="submit" class="action submit primary" title="<?php /* @escapeNotVerified */ echo __('Create an Account') ?>"><span><?php /* @escapeNotVerified */ echo __('Create an Account') ?></span></button>
</div>
<div class="or-another-selection"><?php echo __('or'); ?></div>
<div class="secondary"><a class="action remind" href="<?php /* @escapeNotVerified */ echo $block->getBackUrl() ?>" id="customer-popup-sign-in"><span><?php /* @escapeNotVerified */ echo __('Sign In') ?></span></a></div>
</div>
</form>
<script type="text/x-magento-init">
{
"#customer-popup-register": {
"PHPCuong_CustomerAccount/js/action/customer-authentication-popup": {
"popupTitle": "<?php /* @escapeNotVerified */ echo __('Create an Account'); ?>",
"innerWidth": "600"
}
}
}
</script>
</div>
<?php endif; ?>

 

Customer Authentication Popup in Magento 2

app/code/Wishusucess/CustomerAccount/view/frontend/web/js/action/customer-authentication-popup.js

/**
* Source Wishusucess
* package Wishusucess_CustomerAccount
* Author Wishusucess Magento Development Team
* website https://www.wishusucess.com/
*/
define([
'jquery',
'Magento_Ui/js/modal/modal',
'Magento_Customer/js/customer-data',
'mage/storage',
'mage/translate',
'mage/mage',
'jquery/ui'
], function ($, modal, customerData, storage, $t) {
'use strict';

$.widget('wishusucess.customerAuthenticationPopup', {
options: {
login: '#customer-popup-login',
nextRegister: '#customer-popup-registration',
register: '#customer-popup-register',
prevLogin: '#customer-popup-sign-in'
},

/**
*
* @private
*/
_create: function () {
var self = this,
authentication_options = {
type: 'popup',
responsive: true,
innerScroll: true,
title: this.options.popupTitle,
buttons: false,
modalClass : 'customer-popup'
};

modal(authentication_options, this.element);

// Show the login form in a popup when clicking on the sign in text
$('body').on('click', '.customer-login-link, '+self.options.prevLogin, function() {
$(self.options.register).modal('closeModal');
$(self.options.login).modal('openModal');
self._setStyleCss();
return false;
});

// Show the registration form in a popup when clicking on the create an account text
$('body').on('click', '.customer-register-link, '+self.options.nextRegister, function() {
$(self.options.login).modal('closeModal');
$(self.options.register).modal('openModal');
self._setStyleCss(self.options.innerWidth);
return false;
});

this._ajaxSubmit();
this._resetStyleCss();
},

/**
* Set width of the popup
* @private
*/
_setStyleCss: function(width) {
width = width || 400;
if (window.innerWidth > 786) {
this.element.parent().parent('.modal-inner-wrap').css({'max-width': width+'px'});
}
},

/**
* Reset width of the popup
* @private
*/
_resetStyleCss: function() {
var self = this;
$( window ).resize(function() {
if (window.innerWidth <= 786) {
self.element.parent().parent('.modal-inner-wrap').css({'max-width': 'initial'});
} else {
self._setStyleCss(self.options.innerWidth);
}
});
},

/**
* Submit data by Ajax
* @private
*/
_ajaxSubmit: function() {
var self = this,
form = this.element.find('form'),
inputElement = form.find('input');

inputElement.keyup(function (e) {
self.element.find('.messages').html('');
});

form.submit(function (e) {
if (form.validation('isValid')) {
if (form.hasClass('form-create-account')) {
$.ajax({
url: $(e.target).attr('action'),
data: $(e.target).serializeArray(),
showLoader: true,
type: 'POST',
dataType: 'json',
success: function (response) {
self._showResponse(response, form.find('input[name="redirect_url"]').val());
},
error: function() {
self._showFailingMessage();
}
});
} else {
var submitData = {},
formDataArray = $(e.target).serializeArray();
formDataArray.forEach(function (entry) {
submitData[entry.name] = entry.value;
});
$('body').loader().loader('show');
storage.post(
$(e.target).attr('action'),
JSON.stringify(submitData)
).done(function (response) {
$('body').loader().loader('hide');
self._showResponse(response, form.find('input[name="redirect_url"]').val());
}).fail(function () {
$('body').loader().loader('hide');
self._showFailingMessage();
});
}
}
return false;
});
},

/**
* Display messages on the screen
* @private
*/
_displayMessages: function(className, message) {
$('<div class="message '+className+'"><div>'+message+'</div></div>').appendTo(this.element.find('.messages'));
},

/**
* Showing response results
* @private
* @param {Object} response
* @param {String} locationHref
*/
_showResponse: function(response, locationHref) {
var self = this,
timeout = 800;
this.element.find('.messages').html('');
if (response.errors) {
this._displayMessages('message-error error', response.message);
} else {
this._displayMessages('message-success success', response.message);
}
this.element.find('.messages .message').show();
setTimeout(function() {
if (!response.errors) {
self.element.modal('closeModal');
window.location.href = locationHref;
}
}, timeout);
},

/**
* Show the failing message
* @private
*/
_showFailingMessage: function() {
this.element.find('.messages').html('');
this._displayMessages('message-error error', $t('An error occurred, please try again later.'));
this.element.find('.messages .message').show();
}
});

return $.wishusucess.customerAuthenticationPopup;
});

 

 

Now, Run Following Command:

php bin/magento setup:upgrade

php bin/magento setup:di:compile

php bin/magento setup:static-content:deploy -f

php bin/magento cache:clean

php bin/magento cache:flush

 

Hire Magento 2 Expert Developer to Develop Your Store

GitHub

Related Post:

Custom Shipping Text Filed: Show Custom Text Magento 2

Search AutoComplete: Magento 2 Module Add All Category for Search

Share Product on WhatsApp: With Products Image And URL in Magento 2

 

Recommended Post:

Magento 2.4 Installation Guide: How to Install Magento 2.4.2

Magento Store: Best 36 Magento Websites Example in The World

SEO Packages: How Much Do SEO Packages Cost in India, SEO Pricing

Leave a Reply