SPECIAL OFFER: ENJOY 3 MONTHS OF SHOPIFY FOR $1/MONTH SPECIAL OFFER: ENJOY 3 MONTHS OF SHOPIFY FOR $1/MONTH SPECIAL OFFER: ENJOY 3 MONTHS OF SHOPIFY FOR $1/MONTH SPECIAL OFFER: ENJOY 3 MONTHS OF SHOPIFY FOR $1/MONTH SPECIAL OFFER: ENJOY 3 MONTHS OF SHOPIFY FOR $1/MONTH SPECIAL OFFER: ENJOY 3 MONTHS OF SHOPIFY FOR $1/MONTH SPECIAL OFFER: ENJOY 3 MONTHS OF SHOPIFY FOR $1/MONTH SPECIAL OFFER: ENJOY 3 MONTHS OF SHOPIFY FOR $1/MONTH SPECIAL OFFER: ENJOY 3 MONTHS OF SHOPIFY FOR $1/MONTH SPECIAL OFFER: ENJOY 3 MONTHS OF SHOPIFY FOR $1/MONTH
ajaxlogin

How to create form ajax login in magento 2

In some cases you want to combine some add, edit or delete functions, but you need users to login to be able to do that. Sometimes going to the login page and back to what I was doing it was sometimes quite frustrated about it.

Hence, I wrote this article to create a simple ajax login process. All you have to do is just add the following lines of code to your module, but still need to customize it appropriately so that it is compatible with each case.

First let’s create a block with login functions.

Create new Login.php file added in the directory Module\AjaxLogin\Blog\Form

<?php
namespace Module\AjaxLogin\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');
    }
}

then add files sections.xml added in the directory Module\AjaxLogin\etc\frontend and add the following lines

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Customer:etc/sections.xsd">
    <action name="customer/ajax/login">
        <section name="checkout-data"/>
        <section name="cart"/>
        <section name="customer"/>
    </action>
</config>

Then continue to add a new file default.xml to call create a new login block under the path Module\AjaxLogin\view\frontend\layout

<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <body>
        <referenceContainer name="before.body.end">
            <block class="Module\AjaxLogin\Block\Form\Login" name="ajaxwishlist-popup-login" template="Module_AjaxLogin::login.phtml" /> 
        </referenceContainer>
    </body>
</page>

and according to the new file called in default now add the login.phtml file to the templates directory

<?php
 /** @var \Module\AjaxLogin\Block\Form\Login $block */
?>

<?php if (!$block->customerIsAlreadyLoggedIn()): ?>

    <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 __('Sign in to continue') ?></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="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": {
                    "Module_AjaxLogin/js/action/customer-authentication-popup": {
                        "innerWidth": "400"
                    }
                }
            }
        </script>
    </div>
<?php endif; ?>

Finally add the customer-authentication-popup.js file in the following path: Module\AjaxLogin\view\fontend\web\js\action


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('ajaxlogin.customerAuthenticationPopup', {
        options: {
            login: '#customer-popup-login',
            prevLogin: '.viewlogin'
        },
        _create: function () {
            var self = this,
                authentication_options = {
                    type: 'popup',
                    responsive: true,
                    innerScroll: true,
                    buttons: false,
                    modalClass : 'customer-popup-ajax'
                };

            modal(authentication_options, this.element);

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

            this._ajaxSubmit();
        },

        _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 $.ajaxlogin.customerAuthenticationPopup;
});

Note: Remember where to change ajaxlogin.customerAuthenticationPopup to the frontend name in your routes.xml file eg modulename.customerAuthenticationPopup

Please run the command after completing the steps above when adding it to your module

php bin/magento s:up
php bin/magento s:s:d -f
php bin/magento c:f

Good luck . Please comment below if you have any questions or comments about this article.