How to check email aleady exist using ajax in magento 2

4.7k Views Asked by At

Controller Email.PHP `

public function execute()
    {
        $customerEmail=$this->getRequest()->getParam('email');
        $objectManager=\Magento\Framework\App\ObjectManager::getInstance();
        $CustomerModel = $objectManager->create('Magento\Customer\Model\Customer');
        $CustomerModel->setWebsiteId(1);

        $CustomerModel->loadByEmail($customerEmail);
        $userId = $CustomerModel->getId();
        if ($userId) {
            return 1;
        } else {
            return 0;
        }
    }`

j Query

jQuery(function() {
        var emailAddress = jQuery('#email_address');
        emailAddress.on("change", function () {
           var mail=emailAddress.val();

            jQuery.ajax({
                type: "POST",
                url: "/customer/email/",
                dataType: "json",
                data: {email: mail},
                success: function (exist) {
                    if (exist == 1) {
                       alert("exist");
                    } else if (exist == 0) {
                        alert("exist");
                    }
                },
                error: function (jqXHR, textStatus, errorThrown) {

                        alert("Error " + jqXHR.status + " " + jqXHR.statusText);


                }
            });
        });
    });

I want to check email before clicking create an account button using Ajax, i am not getting to do that, please help me out to solve this issue, thanks in advance.

2

There are 2 best solutions below

1
OBAID On

Simple call a ajax like this

        var mail = '[email protected]';
jQuery.ajax({
    type: "POST",
    url: "/module/checkemail/",
    dataType: "json",
    data: {email: mail},
    success: function (exist) {
        if (exist == 1) {
            // js for email exists
        } else if (exist == 0) {
            // js for not
        }
    },
    error: function (jqXHR, textStatus, errorThrown) {
                   // error handling
    }
});

Than make a controller and load customer by email

$CustomerModel = $objectManager->create('Magento\Customer\Model\Customer');
$CustomerModel->setWebsiteId(1); **//Here 1 means Store ID**
$CustomerModel->loadByEmail($customerEmail);
$userId = $CustomerModel->getId();
if ($userId) {
    return 1;
} else {
    return 0;
}

i

if you get true than email exists.

3
Gaurav Khatri On

It seems like you are trying to validate email address as customer enter his email address. For this you just need minor change in the email address field.

<input type="email" name="email" id="email_address" autocomplete="off" value="<?php echo $block->escapeHtml($block->getFormData()->getEmail()) ?>" title="<?php /* @escapeNotVerified */ echo __('Email') ?>" class="input-text" data-validate="{required:true, 'validate-email':true, 'remote':'<?php echo $this->getUrl('customcustomer/index/uniqueemail', ['_secure' => true]); ?>'}"/>

Create a controller and add you logic in execute method.

<?php 
namespace Gaurav\CustomCustomer\Controller\Index;

use Magento\Framework\App\Action\Action;

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

 /**
 * @var \Magento\Customer\Model\Customer 
 */
 protected $_customerModel;

 /**
 * @param \Magento\Framework\App\Action\Context $context
 * @param \Magento\Framework\Controller\Result\JsonFactory $resultJsonFactory
 */
 public function __construct(
     \Magento\Framework\App\Action\Context $context,
     \Magento\Framework\Controller\Result\JsonFactory $resultJsonFactory,
     \Magento\Customer\Model\Customer $customerModel
 ) {
     $this->resultJsonFactory = $resultJsonFactory;
     $this->_customerModel = $customerModel;
     parent::__construct($context);
 }

 public function execute()
 {
     $resultJson = $this->resultJsonFactory->create();
     $email = $this->getRequest()->getParam('email');
     $customerData = $this->_customerModel->getCollection()
                   ->addFieldToFilter('email', $email);
     if(!count($customerData)) {
       $resultJson->setData('true');
     } else {
       $resultJson->setData('That email is already taken, try another one');
     }
     return $resultJson;
 }
}

I hope this will be helpful to you.