How to use AJAX in magento:
In magento, some of the sections will use of ajax is the good idea to reduce the page loading timing. Ex: If you are using your custom coupon code concept in cart page, will use this ajax. With out page load we can apply the coupon code amount to the total section (code customization we have to do when your applying the custom coupon code).In this scenario we have to use JSON response is the good idea also we have to refresh our total block.
1. Place Textbox with Submit button or href link (with Ajax call, not page load) in cart page.
2. Create AjaxController in Your module (or extend default module with default controller, here AjaxController is my custom controller)
3. Add below code into Submit button or href.
Ex: here am using href
<a href=”javascript:void(0);” onclick=”return callajaxRequestController(Param1,Param2)”>Submit</a>
<script type=”text/javascript”>
function callajaxRequestController(p1,p2)
{
var url=”;
try {
jQuery(“#loadderimage”).show();
jQuery.ajax({
url : ‘<?php echo ‘BASEURL/MyModule/MyController/MyAcction/’;?>’,
dataType : ‘json’,
type : ‘POST’,
data: { p1: 10, p2 : 100},
success : function(data){
if(data.status == 1){
jQuery(“#loadderimage”).hide();
jQuery(‘.payment-totals-table’).replaceWith(data.refreshtotalBLK);
}else{
if(data.status == 0){
alert(data.message);
}
}
}
});
}catch(e) {}
}
</script>
4. Now your ajax acction is ready from template file. Now you have to write your acction from controller file.Like below
public function MyAcction(){
$p1 = Mage::app()->getRequest()->getPost(‘p1’);
……….. write yourcode …….
…………………………….
……………………………
$response[‘status’] = 0;
$sidebar= $this->getLayout()->createBlock(‘checkout/cart_totals’)->setTemplate(‘checkout/cart/totals.phtml’)->toHtml();
$response[‘refreshtotalBLK’] = $sidebar;
return $this->getResponse()->setBody(Mage::helper(‘core’)->jsonEncode($response));
}
5. Yes now your controller file also ready. Once yor call your request, the controller action will trigger also your action will send your response as Json. In your ajax call you can get this json value and use as it is.
6. jQuery(‘.payment-totals-table’).replaceWith(data.refreshtotalBLK), this code will use to refresh your total block once your changes is done from the total section