Generally speaking, AJAX can help to enhance user experience of Magento-based websites. Magento is optimized to make it easy to apply AJAX using third-party JS libraries like jQuery and Prototype. In this article, I’ll brief you the basic steps of developing Magento extensions using AJAX and JSON. As an example, AJAX Login extension developed by us will be introduced.

In default, Magento will redirect the customers to another page when logining successfully. It is annoying as customers will get lost when they are redirected to another page. In order to solve this problem and increase the customers' retention, we rewrite the login module of Magento into AJAX Login in the following ways:

  • Copy the original Magento Login module and setup a new one. (We don’t discuss about this as there is a lot of articles discussing how to setup a new module in Magento)
  • Modify the codes of the Login Controller and response in JSON on the server side;
  • Add Javascript on the front-end to parse JSON when customer login happens.
The basic idea above is simple and below are some details. Firstly, let's start with the server side.

// Here, only the key parts are showed.
public function loginPostAction()
{		
	$result = array();		
	$session = $this->_getSession();		
	
	$login = $this->getRequest()->getPost('login');	
	if (!empty($login['username']) && !empty($login['password'])) {
		try {
			if ($session->login($login['username'], $login['password'])){
				$result['logined'] = 1;
				$result['user'] = $session->getCustomer()->getName();
			}
				
			// If this user just confirmed registration, it need to send him/her a confirmation email.
		} catch (Exception $e) {
			// Error handling
		}
	} 
	else{
		// Username or password is wrong.
	}
	$this->getResponse()->setBody(Mage::helper('core')->jsonEncode($result));
}

We use the jsonEncode() function from the core helper of Magento to convert a PHP array into a JSON object.

$this->getResponse()->setBody(Mage::helper('core')->jsonEncode($result));

Then in the frontend of the site, we add some JS codes to handle the JSON passed back from the server side.

var dataForm = new VarienForm('login-form', true);
if (!dataForm.validator.validate()){
	return;
}
			
jQuery.post(	
    '<?php echo $this->getUrl("mglogin/index/loginpost") ?>',
    jQuery("#login-form").serialize(),
    function(data){
	var result = eval("(" + data + ")");
	if (result.logined){
		// Login succeeded.
	}else{
		// Login failed.
	}
});

We could see from the above codes that programming with AJAX in Magento is pretty straight forward and similar to many other programming frameworks.