Magento: Using AJAX with Prototype JS

This article shows how to use AJAX on Magento with Prototype Javascript Library.

Scenario

I had one scenario where I had to check whether a customer is already registered or not via AJAX.

– User will enter his/her email address in a text box and press the ‘Continue’ button.
– After that, I need to check if that email is already registered or not.
– If the email is already registered, then I have to show an alert with some message in it.
– If the email is not registered, then I need to proceed to next Javascript function.

Solution

Below is the text fieldcode where user have to type his/her email address. Also, there is a ‘Continue’ button code. When the ‘Continue’ button is clicked, then isRegisteredEmail() Javascript function is called.


<input type="text" name="user_email" id="user_email" title="<?php echo Mage::helper('core')->quoteEscape($this->__('Your Email')) ?>" class="input-text validate-email required-entry" />

<button type="button" class="button" onclick="isRegisteredEmail();"><span><span><?php echo $this->__('Continue') ?></span></span></button>

Below is the isRegisteredEmail() Javascript function. This function calls your module’s controller’s “checkEmailAction()” function via AJAX ‘get’ method. It passes user’s email as parameter. Based on the response value, it will alert the user or proceed to nextStep function. Here, I have assumed that your module’s name is “YourModule” and your controller name is “Xyz“.


function isRegisteredEmail()
{
    new Ajax.Request('<?php echo $this->getUrl('YourModule/xyz/checkemail') ?>', {
      method:'get',
      parameters: {email: document.getElementById("user_email").value},
      onSuccess: function(transport) {      
        var response = JSON.parse(transport.responseText);      
        if (response.error == 1) {
            alert(response.message);
            return false;
        } else {            
            proceedToNextStep();
        }
      },
      onFailure: function() {             
          alert('Something went wrong...'); 
          console.log('Something went wrong...');
          return false;
      }
    });
}

Here is the function to check registered email which is to be written in your controller’s class (app/code/community/YourNamespace/YourModule/controllers/XyzController.php).


public function checkEmailAction() 
{       
    $customer = Mage::getModel('customer/customer');
    $customer->setWebsiteId(Mage::app()->getWebsite()->getId());
    $customer->loadByEmail($this->getRequest()->getParam('email'));
    
    $data = $customer->getData();
    
    if (!empty($data)) {                
        $result = array('error' => 1, 'message' => Mage::helper('checkout')->__('An account is already registered under this email address'));
    } else {    
        $result = array('error' => 0);
    }
    
    $this->getResponse()->setBody(Mage::helper('core')->jsonEncode($result));
}

Hope this helps. Thanks.