Get Extension from Magento Connect
I have few blog posts regarding working with Ajax on Magento.
http://subesh.com.np/category/ajax/. And I see many people visiting those pages to get the information on working with Ajax in Magento. Sensing the need of developer I came up with an idea of making the whole process into a module in an effort to give back to the Magento community. I’ve tried to make the module simple for now, which of course can be extended a lot to incorporate all kinds of needs. But for now, if I may say, there are roughly these two things you might want to do (Purely in Magento terms).
- Request to a controller with params, do some changes in the model, set error/success message and show those message to the user.
- Next, perform all the actions as #1 and in addition to that refresh the content of certain HTML elements.
This module has been devised just to meet these two actions. In addition, the module is loader ready and has by default a floating message block.
Followings are the ways you can perform those two actions using this module.
Overview
The core functionality implemenation is done in js/ajaxify/ajaxify.js file. If you look into that file, you will find a JS Class. The constructor for the class are:
- URL of the request controller.
- Parameters (JSON object) to be sent as request params to the controller.
For request and show message just call
request() method, while if you want an HTML element to be updated then call
requestUpdate(‘elementID’), with element ID in the parameter.
Request to a controller with params, do some changes in the model, set error/success message and show those message to the user.
This is how you initillize the JS Object.
[source lang=”javascript”]
<script type="text/javascript">
var ajxObj = new SpAjaxify(‘<?php echo $this->getUrl(‘ajaxify/index/test’) ?>’, {id: ‘12’, value: ‘23’});
ajxObj.request(); // Request
</script>
[/source]
To set the message error/success you have to use ajaxify/session model, because it is from this model the messages are shown.
[source lang=”php”]
/**
* Always use this session to set your error or success message
*
* @return Sp_Ajaxify_Model_Session
*
* PLEASE DO NOT EDIT THIS
*/
protected function _getSession()
{
return Mage::getSingleton(‘ajaxify/session’);
}
// Set Error message .
$this->_getSession()->addError(‘Item was not added to the shopping cart.’);
// Set Success message
$this->_getSession()->addSuccess(‘Item was successfully added to the shopping cart.’);
[/source]
In addition to the above refresh the content of certain HTML elements.
[source lang=”javascript”]
<script type="text/javascript">
var ajxObj = new SpAjaxify(‘<?php echo $this->getUrl(‘ajaxify/index/test’) ?>’, {id: ‘12’, value: ‘23’});
ajxObj.requestUpdate(‘sidebar_cart’); // Ajax request with parameter to update the HTML element.
</script>
[/source]
The source also contains description of the hidden logic to manage templates/layouts required.