AJAX is a great technology that is used to improve user experience and avoid page reloads, but how can you use it in your own Magento modules? Let’s explore…
1) You should either create a controller, for example: Namespace/YourModule/controllers/AjaxController.php or create a new action in an existing controller
2) To create an action in your controller, such as indexAction(), you would add this code
public function indexAction() { $this->loadLayout(); $this->renderLayout(); }
3) Then add to yourlayout.xml (example: app/design/frontend/…/…/layout/yourlayout.xml) next code
<yourmodule_ajax_index> <block type="yourmodule/yourblock" name="root" template="path/template.phtml" /> </yourmodule_ajax_index>
where yourmodule is the frontend router, ajax is the controller name and index is the action name
4) Then you need to update the layout in config.xml
<layout> <updates> <yourmodule> <file>yourlayout.xml</file> </yourmodule> </updates> </layout>
5) After this, the instance of your YourBlock class will be available in template.phtml
6) And finally, you need to call your Ajax controller with JavaScript or JQuery, for example:
xmlhttp.open("GET","yourmodule/ajax/index/someval/"+value,true);
or
jQuery.post(“yourmodule/ajax/index”, {someval: value}, function(data){...});
You may also want to read:
Read more: