Magento Tutorials

How to Use AJAX Requests in Magento

AJAX is a great technology that is used to improve user experience and avoid page reloads. Upon searching, you can get various topics relating to AJAX such as AJAX add to cart/ call/ login/ loader/ form submit or controller… However, today, we will explore about the AJAX requests and how can you use it in your own Magento modules.

Step 1: You should either create a controller (for example: Namespace/YourModule/controllers/AjaxController.php) or create a new action in an existing controller

Step 2: To create an action in your controller, such as indexAction(), add this code:

public function indexAction()
{
$this->loadLayout();
$this->renderLayout();
}
Step 3:

Add to your layout.xml (example: app/design/frontend/…/…/layout/yourlayout.xml) the following 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.

Step 4: Then you need to update the layout in config.xml

<layout>
    <updates>
        <yourmodule>
            <file>yourlayout.xml</file>
        </yourmodule>
    </updates>
</layout>
Step 5:

After this, the instance of your YourBlock class will be available in template.phtml

Step 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){…});


Hope this helps!

Dom

A knowledge craver who always strive to be wiser everyday.

Subscribe
Notify of
guest

1 Comment
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
Uponeet
Uponeet
4 months ago

With the missions in House of Hazards, can you complete the challenges of this game? Try to overcome them.