Running Magento 1.9.0.1 CE
I've created an AJAX version of the discount-form used in Magento to process coupons in Magento with the help of this tutorial: http://www.lelandcope.com/2012/04/how-to-create-an-ajax-coupon-discount-code-box-in-magento/
Basically, I left the previous discount form in place (verifying that there were no conflicts) so that I could verify my coupons quickly in case my AJAX form didn't work.
The gist is, my AJAX form is rejecting EVERY coupon. Here is the code summary.
AJAX Form HTML:
<div class="box">
<strong class="ttl">DISCOUNT CODE</strong>
<p>Enter your coupon code if you have one</p>
<form id="discountcode-form" action="<?= $this->getUrl('checkout/cart/couponPost') ?>" name="discountcode-form" method="post">
<div class="text discount-code"><input type="text" name="coupon_code" value="SUBMIT YOUR CODE" /></div>
<input type="submit" class="btn-apply" value="APPLY"/>
</form>
</div>
AJAX Form jQuery (in no-conflict mode):
<script type="text/javascript">
jQuery('#discountcode-form').submit(function(e)
{
console.log("entering script");
e.preventDefault();
jQuery.ajax({
url:jQuery('#discountcode-form').attr('action'),
type:'POST',
data:'ajax=true&'+jQuery('#discountcode-form').serialize(),
success:function(data)
{
if(data != '')
{
console.log("error messages")
}
}
});
});
</script>
And finally, the piece of the puzzle I believe to be responsible for the issue - CartController.php:
<?php
require_once 'Mage/Checkout/controllers/CartController.php';
class MyModules_CouponProcessor_CartController extends Mage_Checkout_CartController
{
function couponPostAction()
{
// if not ajax have parent deal with result
if(!isset($_POST['ajax']))
{
parent::couponPostAction();
return;
}
$msg = '';
$couponCode = (string) $this->getRequest()->getParam('coupon_code');
if ($this->getRequest()->getParam('remove') == 1) {
$couponCode = '';
}
$oldCouponCode = $this->_getQuote()->getCouponCode();
if (!strlen($couponCode) && !strlen($oldCouponCode)) {
$this->_goBack();
return;
}
try {
$this->_getQuote()->getShippingAddress()->setCollectShippingRates(true);
$this->_getQuote()->setCouponCode(strlen($couponCode) ? $couponCode : '')
->collectTotals()
->save();
if ($couponCode) {
if ($couponCode == $this->_getQuote()->getCouponCode()) {
$this->_getSession()->addSuccess(
$this->__('Coupon code "%s" was applied.', Mage::helper('core')->htmlEscape($couponCode))
);
}
else {
$msg = $this->__('Coupon code "%s" is not valid.', Mage::helper('core')->htmlEscape($couponCode));
}
} else {
$this->_getSession()->addSuccess($this->__('Coupon code was canceled.'));
}
} catch (Mage_Core_Exception $e) {
$msg = $e->getMessage();
} catch (Exception $e) {
$msg = $this->__('Cannot apply the coupon code.');
Mage::logException($e);
}
echo $msg;
}
}
Am I doing something wrong in my CartController? The AJAX seems to work fine.