Ajax in Magento can be pretty troublesome.Because you will need to take controllers and layout into account.And I almost used up a whole day trying to make ajax work. Here are some of the steps I’d like to share so that you will not waste lots of your time, before making this work
.
Let’s first know in Magento terms what we need.
Controller: The url on which Ajax will work on, or the 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 to handle the requested URL and return HTML if required.
Block: The block to call through layout for the above controller.
Now lets be descriptive.
If you want to show a loader while request is being processed just add the following whereever you like in the phtml page.First fetch the Javascript.
<script src="<?php echo $this->getJsUrl() ?>mage/adminhtml/loader.js" type="text/javascript"></script>
Then echo the loader which pops up. This loader will be similar to that of the admin.
<div id="loadingmask" style="display: none;">
<div class="loader" id="loading-mask-loader"><img src="<?php echo str_replace("index.php/","",$this->getUrl()) ?>skin/adminhtml/default/default/images/ajax-loader-tr.gif" alt="<?php echo $this->__('Loading...') ?>"/><?php echo $this->__('Loading...') ?></div>
<div id="loading-mask"></div>
</div>
Now to Call Ajax, use the following lines
/*Please note that the URL is created in reloadurl. Also see that the response text will be echoed in div with id=output-div*/
var reloadurl = '<?php echo $this->getUrl('router/controller/action') ?>';
Element.show('loadingmask');
new Ajax.Request(reloadurl, {
method: 'post',
parameters: "Params_Here",
onComplete: function(transport) {
Element.hide('loadingmask');
$('output-div').innerHTML = "";
$('output-div').innerHTML = transport.responseText;
}
});
After the Ajax Request 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();
}
}
And here is the main part in layout where I spent most of my time in. Since in layout we will have to define reference where the html will echo (Most of the times), i got stuck here, because i need to echo the output on the div with id output-div not in any reference.And the trick is to name the layout as root and output as html. Like the following:
<module_controller_action> <block type="module/block" name="root" output="toHtml" template="module/template.phtml"/> </module_controller_action>
You are done now! What ever you write or echo in phtml file you will see populated in the DIV. Now you can treat block as normally as you do before.
Happy Coding!!

Can you explain a little more about setting the frontend router in the config file?
Thanks,
Jason
Routers are the path you specify to get to the controller file it is defined in config.xml with Xpath config/frontend/router and inside this Frontend name is what is used in url to get to the controller.
Thanks
I don’t think I’m doing it right.
I created a custom module that loads into a cms page. When the user interacts with the info on the page, I am wanting to call php functions from the custom module.
As far as I can tell, all of my code is working, but I am not getting any returned data from the ajax call.
I added a router to my custom module config.xml
I am very sorry to bug you, but do you have any other tips or advice?
Thanks,
Jason
I think I have it figured out now. I just need to figure out how to control the returned data now.
Thank you for your time!
Hi,
Sorry I’ve n’t been able to reply your last message. So by now I think you have figured out how to get your controller going. After that you need to create a layout for that controller’s action like the layout as suggested above.
As you can see you can specify the block type and template as well in that layout. So this will be as easy as creating a layout for any custom controller.
And after that you should have the “output-div” (id of the div where you want to echo the response).
Hi Subesh, first of all , thanks for the post which give me a jumpstart into Magento Ajax .
I have followed your method, however, I got the whole page loaded into the “output-div” , instead of the block that define in the layout.
I have tried to use $this->loadLayout(’module_controller_action’)->renderLayout() in the actionAction , but it does not give any response.
Actually I want to load the product list by ajax
4
product_list_toolbar
Any clue ?
It seems problem has been solved after clearing the cache. thanks …
Hi, it is good to mention that this Ajax object is coming with the Prototype JavaScript framework which Magento uses. Better approach in your example is using the Ajax.Updater instead of Ajax.Request because you are updating the content of a div. With Ajax.Updater you do not need the 2 lines:
$(’output-div’).innerHTML = “”;
$(’output-div’).innerHTML = transport.responseText;
Another good option of Ajax.Updater is evalScripts ( default value is false). Setting it to true makes execution of javascript functionality within the responseText.
Ajax.Request is good when you process JSON response or when you do not need to receive any response.
Thanks for the Tips!
Hi Subesh, thanks for the info.
The updater Miro mentioned can also be run easily at set intervals as a PeriodicalUpdater:
new Ajax.PeriodicalUpdater(’someDiv’, reloadurl, {
method: ‘post’,
parameters: { from : ‘10000′ },
insertion: Insertion.Top,
frequency: 1,
decay: 2,
onComplete: function() {
Element.hide(’loadingmask’);
}
});
Sorry for lack of code formatting
Note: you would probably want something else to display when periodically updating than the standard loading mask which blocks the entire screen.
Thank You for the Tips!
Hi,
great article, but Im sorry to say that I cant manage to get this to work. I do reach my controller and can see the debug data there, but I cant load the template, it just load a whole magento page. Should the block be just an empty shell without any methods? My layout-file looks like this
[?xml version="1.0"?]
[layout version="0.1.0"]
[module_address_getaddresses]
[block type="module/address_list" name="root" output="toHtml" template="module/address/list.phtml"/]
[/module_address_getaddresses]
[/layout]
All help is greatly appreciated.
You are going well.. I think..and your layout files seems okai. It should work. Plz try to find out that your layout is being used or not. I guess that must be the problem or else cache might be the problem.
Thanks.
Hi,
thanks for your reply. I’ve now got it working, I was just missing the [layout][updates]-block in my config.xml for the frontend.
Thanks again, and great article.
Can you give example of getUrl(’router/controller/action’) ?>’; in magento ?
Thanks.
For Example if you viewing category view page then
Router: catalog
Controller: category
Action : viewAction.
Thanks.
hey, Thanks for the great info
i’m a new developer in magento and i was wondering, if i should create a custom module for the action and layout, or just attach it to some other module…?
thanks
You can attach to some existing module.. It depends upon what you need.
I worked it out, and it’s working beautifully, thanks for the great info
Hi..was going through ur ajax post..right now i have a problem..
I am developing ajax add to cart..I have almost done it to say..I am able to add products to cart and again I am able to read the sessions of cart to mycart widget..
the problem comes here..how do i read the image of specific product and I have to add a delete option..well u know mycart operations..
So tel me how to get the image and delete operation..
Or better to say how to access sidebar.phtml from root folder of magento..either one will solve the problem..
Madhu, I think you have done the “difficult” part….if you have successfully added product to cart!
Here’s one tip for your issue, but do you have controller of your own? If yes then prepare a layout for that controller and assign block & template and… if you can access cart session as you say then showing a list of product added should not be a problem. Please the 4th and 5th snippet of code above.
Thanks.
Hi Subesh,
I want to firstly say thank you for your blog, really everytime I read something from you, you can be sure that I have learned something, and I am very greatful for that.
Bro, I’m trying to get this ajax working, and I have override my controller and it works.
I have added all the scripts and as far as I can see this all is working too, but bro, can you tell me what I should make the href?
I have a bunch of tabs..and they load content dynamically but, my page load times is taking a hit, so some of these tabs I would like to bring in the content with ajax.
My controller function looks like this:
public function actionAction() { error_log('Begin action'); //Get current layout state $this->loadLayout(); $this->getLayout()->createBlock( 'Mage_Core_Block_Template', 'Mage_Catalog_Block_Category_View', array('template' => 'catalog/category/view.phtml') ); //$this->getLayout()->createBlock('footer')->append($block); //Release layout stream $this->renderLayout(); error_log('End action'); }Can you tell me if that is correct?
Thank you so very much man, I really appreciate it!
impi
Hi,
I don’t think you code will show the content, easiest way to load content is write only this in your controller
And next prepare a layout file and follow the instruction above in the post.
Thanks.
It didnt work initially for me.
After digging in /js/mage/adminhtml/loader.js
i had to append paramaeters with &form_key=getFormKey();?>
like this
parameters: ‘QueryString&form_key=getFormKey();?>’
Let me know if this is because of some change in new magento version or if i missed any step.Anyway its working for me now
thanks for a great post.