How to Handle AJAX Requests in Magento

Sometimes its very troublesome to implement Ajax with Magento. Actaully you will have to couple controllers and layout. Here in this post , I have explained few simple step to handle this.

Let’s first know Magento terms:

Controller: This is a request URL. You will have to set up the controller with its frontend router set in config.xml and its corresponding controller class.

Layout: Layout will handle the requested URL and return HTML.

Block: The block to call through layout for the above controller.

Make Ajax Call:
var loadurl = ‘<?php echo $this->getUrl(‘ACTIONPATH‘) ?>’;
Element.show(‘MYPANEL’);
new Ajax.Request(loadurl, {
method: ‘post’,
parameters: “Params_Here”,
onComplete: function(transport) {
Element.hide(‘MYPANEL’);
$(‘output-div’).innerHTML = “”;
$(‘output-div’).innerHTML = transport.responseText;
}
});

After the Ajax Call is made it goes to your controller’s action, which in turn sees to your layout as follows:
class Namespace_module_frontendController extends Mage_Core_Controller_Front_Action
{
public function actionAction(){
$this->loadLayout()->renderLayout();
}
}

As in layout we will have to define reference where the html will be displayed. you can make changes according to your requirement to reference properties;
<module_controller_action>
<block type=“module/block” name=“root” output=“toHtml” template=“module/template.phtml”/>
</module_controller_action>


 

You may like these posts