Apply Magento Coupon in Ajax Without Redirecting to Cart Page Unicorn Meta Zoo #1: Why another...

c++ diamond problem - How to call base method only once

How would this chord from "Rocket Man" be analyzed?

Arriving in Atlanta after US Preclearance in Dublin. Will I go through TSA security in Atlanta to transfer to a connecting flight?

AI positioning circles within an arc at equal distances and heights

Retract an already submitted recommendation letter (written for an undergrad student)

Would reducing the reference voltage of an ADC have any effect on accuracy?

Is there any hidden 'W' sound after 'comment' in : Comment est-elle?

Password Generator in batch

Where did Arya get these scars?

My admission is revoked after accepting the admission offer

Trumpet valves, lengths, and pitch

Do you need a weapon for Thunderous Smite, and the other 'Smite' spells?

Second order approximation of the loss function (Deep learning book, 7.33)

A Paper Record is What I Hamper

Can you stand up from being prone using Skirmisher outside of your turn?

My bank got bought out, am I now going to have to start filing tax returns in a different state?

Need of separate security plugins for both root and subfolder sites Wordpress?

Why did C use the -> operator instead of reusing the . operator?

Is a 5 watt UHF/VHF handheld considered QRP?

What is this word supposed to be?

Is Bran literally the world's memory?

Protagonist's race is hidden - should I reveal it?

Identify story/novel: Tribe on colonized planet, not aware of this. "Taboo," altitude sickness, robot guardian (60s? Young Adult?)

How to not starve gigantic beasts



Apply Magento Coupon in Ajax Without Redirecting to Cart Page



Unicorn Meta Zoo #1: Why another podcast?
Announcing the arrival of Valued Associate #679: Cesar ManaraCustom AJAX discount-form not processing couponsNeed help in add to cart with ajaxrefresh page in magento without reloading - ajaxAjax redirecting to system configuration page in admin custom moduleMagento Multiple coupon apply on cartsame coupon code should apply for diferent conditionsCoupon code form and show div onSuccess / onFailureApply coupon code only for specific categoryMagento 2:- Apply custom coupon codeDiscount/Coupon Code Block not working on onepage checkout pageCreate an AJAX coupon code button on checkout step





.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{ margin-bottom:0;
}







4















I have coupon code on sidebar on my product categories list, cart and checkout page. Whenever I'm trying to add coupon code while being on the product or category list page or checkout page, it is taking me to the cart page. Is there any way I can make it apply on the same page without redirecting or reloading with the help of ajax?



<?php echo $this->getMessagesBlock()->toHtml(); ?>
<div class="coupon bg-gray">
<form id="discount-coupon-form" action="<?php echo $this->getUrl('checkout/cart/coupon') ?>" name="discountcode-form" method="post">
<div class="discount">
<h2><?php echo $this->__('Discount Codes') ?></h2>
<div class="discount-form">
<!--<label for="coupon_code"><?php echo $this->__('Discount Codes') ?></label>-->
<input type="hidden" name="remove" id="remove-coupone" value="0" />
<!--<div class="field-wrapper">-->
<input class=" form-control" type="text" placeholder="Enter Coupon Code" id="coupon_code" name="coupon_code" value="<?php echo $this->escapeHtml($this->getCouponCode()) ?>" />
<!--<div class="button-wrapper">-->
<!-- <button type="button" title="<?php echo $this->__('Apply') ?>" class="btn-danger" onclick="discountForm.submit(false)" value="<?php echo $this->__('Apply') ?>"><span><span><?php echo $this->__('REEDEM COUPON') ?></span></span></button>--><?php $block = $this->getLayout()->createBlock('checkout/onepage_link'); ?> <?php if ($block->isPossibleOnepageCheckout()):?> <?php if ($block->isDisabled()):?> <input type="submit" title="Minimum order should be Rs.300 or above" value="<?php echo $this->__('REEDEM COUPON') ?>" class="btn-danger btn-checkoutno-checkout" disabled="disabled" /> <?php else: ?> <input type="submit" title="Minimum order should be Rs.300 or above" value="<?php echo $this->__('REEDEM COUPON') ?>" class="btn-danger" />
<?php endif?> <?php endif?>


<?php if(strlen($this->getCouponCode())): ?>
<button type="button" title="<?php echo $this->__('Cancel') ?>" class="button2 cancel-coupon" onclick="discountForm.submit(true)" value="<?php echo $this->__('Cancel') ?>"><span><span><?php echo $this->__('Cancel') ?></span></span>
</button>
<?php endif;?>

<!--</div>-->
<!--</div>-->
</div>
</div>
</form>
</div>
<script type="text/javascript">

//<![CDATA[

function updateCoupon(reqid) {

var reqid;

if(reqid == 2) { $('coupon_code').setValue(''); }

$('discount-coupon-form').request({

method: 'post',

onComplete: payment.onComplete,

onSuccess: payment.onSave,

onFailure: checkout.ajaxFailure.bind(checkout),

})

}

//]]>

</script>









share|improve this question
















bumped to the homepage by Community 3 hours ago


This question has answers that may be good or bad; the system has marked it active so that they can be reviewed.






















    4















    I have coupon code on sidebar on my product categories list, cart and checkout page. Whenever I'm trying to add coupon code while being on the product or category list page or checkout page, it is taking me to the cart page. Is there any way I can make it apply on the same page without redirecting or reloading with the help of ajax?



    <?php echo $this->getMessagesBlock()->toHtml(); ?>
    <div class="coupon bg-gray">
    <form id="discount-coupon-form" action="<?php echo $this->getUrl('checkout/cart/coupon') ?>" name="discountcode-form" method="post">
    <div class="discount">
    <h2><?php echo $this->__('Discount Codes') ?></h2>
    <div class="discount-form">
    <!--<label for="coupon_code"><?php echo $this->__('Discount Codes') ?></label>-->
    <input type="hidden" name="remove" id="remove-coupone" value="0" />
    <!--<div class="field-wrapper">-->
    <input class=" form-control" type="text" placeholder="Enter Coupon Code" id="coupon_code" name="coupon_code" value="<?php echo $this->escapeHtml($this->getCouponCode()) ?>" />
    <!--<div class="button-wrapper">-->
    <!-- <button type="button" title="<?php echo $this->__('Apply') ?>" class="btn-danger" onclick="discountForm.submit(false)" value="<?php echo $this->__('Apply') ?>"><span><span><?php echo $this->__('REEDEM COUPON') ?></span></span></button>--><?php $block = $this->getLayout()->createBlock('checkout/onepage_link'); ?> <?php if ($block->isPossibleOnepageCheckout()):?> <?php if ($block->isDisabled()):?> <input type="submit" title="Minimum order should be Rs.300 or above" value="<?php echo $this->__('REEDEM COUPON') ?>" class="btn-danger btn-checkoutno-checkout" disabled="disabled" /> <?php else: ?> <input type="submit" title="Minimum order should be Rs.300 or above" value="<?php echo $this->__('REEDEM COUPON') ?>" class="btn-danger" />
    <?php endif?> <?php endif?>


    <?php if(strlen($this->getCouponCode())): ?>
    <button type="button" title="<?php echo $this->__('Cancel') ?>" class="button2 cancel-coupon" onclick="discountForm.submit(true)" value="<?php echo $this->__('Cancel') ?>"><span><span><?php echo $this->__('Cancel') ?></span></span>
    </button>
    <?php endif;?>

    <!--</div>-->
    <!--</div>-->
    </div>
    </div>
    </form>
    </div>
    <script type="text/javascript">

    //<![CDATA[

    function updateCoupon(reqid) {

    var reqid;

    if(reqid == 2) { $('coupon_code').setValue(''); }

    $('discount-coupon-form').request({

    method: 'post',

    onComplete: payment.onComplete,

    onSuccess: payment.onSave,

    onFailure: checkout.ajaxFailure.bind(checkout),

    })

    }

    //]]>

    </script>









    share|improve this question
















    bumped to the homepage by Community 3 hours ago


    This question has answers that may be good or bad; the system has marked it active so that they can be reviewed.


















      4












      4








      4








      I have coupon code on sidebar on my product categories list, cart and checkout page. Whenever I'm trying to add coupon code while being on the product or category list page or checkout page, it is taking me to the cart page. Is there any way I can make it apply on the same page without redirecting or reloading with the help of ajax?



      <?php echo $this->getMessagesBlock()->toHtml(); ?>
      <div class="coupon bg-gray">
      <form id="discount-coupon-form" action="<?php echo $this->getUrl('checkout/cart/coupon') ?>" name="discountcode-form" method="post">
      <div class="discount">
      <h2><?php echo $this->__('Discount Codes') ?></h2>
      <div class="discount-form">
      <!--<label for="coupon_code"><?php echo $this->__('Discount Codes') ?></label>-->
      <input type="hidden" name="remove" id="remove-coupone" value="0" />
      <!--<div class="field-wrapper">-->
      <input class=" form-control" type="text" placeholder="Enter Coupon Code" id="coupon_code" name="coupon_code" value="<?php echo $this->escapeHtml($this->getCouponCode()) ?>" />
      <!--<div class="button-wrapper">-->
      <!-- <button type="button" title="<?php echo $this->__('Apply') ?>" class="btn-danger" onclick="discountForm.submit(false)" value="<?php echo $this->__('Apply') ?>"><span><span><?php echo $this->__('REEDEM COUPON') ?></span></span></button>--><?php $block = $this->getLayout()->createBlock('checkout/onepage_link'); ?> <?php if ($block->isPossibleOnepageCheckout()):?> <?php if ($block->isDisabled()):?> <input type="submit" title="Minimum order should be Rs.300 or above" value="<?php echo $this->__('REEDEM COUPON') ?>" class="btn-danger btn-checkoutno-checkout" disabled="disabled" /> <?php else: ?> <input type="submit" title="Minimum order should be Rs.300 or above" value="<?php echo $this->__('REEDEM COUPON') ?>" class="btn-danger" />
      <?php endif?> <?php endif?>


      <?php if(strlen($this->getCouponCode())): ?>
      <button type="button" title="<?php echo $this->__('Cancel') ?>" class="button2 cancel-coupon" onclick="discountForm.submit(true)" value="<?php echo $this->__('Cancel') ?>"><span><span><?php echo $this->__('Cancel') ?></span></span>
      </button>
      <?php endif;?>

      <!--</div>-->
      <!--</div>-->
      </div>
      </div>
      </form>
      </div>
      <script type="text/javascript">

      //<![CDATA[

      function updateCoupon(reqid) {

      var reqid;

      if(reqid == 2) { $('coupon_code').setValue(''); }

      $('discount-coupon-form').request({

      method: 'post',

      onComplete: payment.onComplete,

      onSuccess: payment.onSave,

      onFailure: checkout.ajaxFailure.bind(checkout),

      })

      }

      //]]>

      </script>









      share|improve this question
















      I have coupon code on sidebar on my product categories list, cart and checkout page. Whenever I'm trying to add coupon code while being on the product or category list page or checkout page, it is taking me to the cart page. Is there any way I can make it apply on the same page without redirecting or reloading with the help of ajax?



      <?php echo $this->getMessagesBlock()->toHtml(); ?>
      <div class="coupon bg-gray">
      <form id="discount-coupon-form" action="<?php echo $this->getUrl('checkout/cart/coupon') ?>" name="discountcode-form" method="post">
      <div class="discount">
      <h2><?php echo $this->__('Discount Codes') ?></h2>
      <div class="discount-form">
      <!--<label for="coupon_code"><?php echo $this->__('Discount Codes') ?></label>-->
      <input type="hidden" name="remove" id="remove-coupone" value="0" />
      <!--<div class="field-wrapper">-->
      <input class=" form-control" type="text" placeholder="Enter Coupon Code" id="coupon_code" name="coupon_code" value="<?php echo $this->escapeHtml($this->getCouponCode()) ?>" />
      <!--<div class="button-wrapper">-->
      <!-- <button type="button" title="<?php echo $this->__('Apply') ?>" class="btn-danger" onclick="discountForm.submit(false)" value="<?php echo $this->__('Apply') ?>"><span><span><?php echo $this->__('REEDEM COUPON') ?></span></span></button>--><?php $block = $this->getLayout()->createBlock('checkout/onepage_link'); ?> <?php if ($block->isPossibleOnepageCheckout()):?> <?php if ($block->isDisabled()):?> <input type="submit" title="Minimum order should be Rs.300 or above" value="<?php echo $this->__('REEDEM COUPON') ?>" class="btn-danger btn-checkoutno-checkout" disabled="disabled" /> <?php else: ?> <input type="submit" title="Minimum order should be Rs.300 or above" value="<?php echo $this->__('REEDEM COUPON') ?>" class="btn-danger" />
      <?php endif?> <?php endif?>


      <?php if(strlen($this->getCouponCode())): ?>
      <button type="button" title="<?php echo $this->__('Cancel') ?>" class="button2 cancel-coupon" onclick="discountForm.submit(true)" value="<?php echo $this->__('Cancel') ?>"><span><span><?php echo $this->__('Cancel') ?></span></span>
      </button>
      <?php endif;?>

      <!--</div>-->
      <!--</div>-->
      </div>
      </div>
      </form>
      </div>
      <script type="text/javascript">

      //<![CDATA[

      function updateCoupon(reqid) {

      var reqid;

      if(reqid == 2) { $('coupon_code').setValue(''); }

      $('discount-coupon-form').request({

      method: 'post',

      onComplete: payment.onComplete,

      onSuccess: payment.onSave,

      onFailure: checkout.ajaxFailure.bind(checkout),

      })

      }

      //]]>

      </script>






      ce-1.9.1.0 ajax coupon-codes






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Jul 5 '18 at 4:54









      Teja Bhagavan Kollepara

      2,99241950




      2,99241950










      asked Jun 30 '15 at 11:43









      Shoeb MirzaShoeb Mirza

      181213




      181213





      bumped to the homepage by Community 3 hours ago


      This question has answers that may be good or bad; the system has marked it active so that they can be reviewed.







      bumped to the homepage by Community 3 hours ago


      This question has answers that may be good or bad; the system has marked it active so that they can be reviewed.
























          2 Answers
          2






          active

          oldest

          votes


















          0














          There are lot issue in your code.



          JavaScript is wrong.you have call opcheckout.js function payment.payment.onSave and checkout.ajaxFailure.bind(checkout), etc which does not work on all pages.



          So you need to Custom code which will apply coupon code on ajax on all pages



          You can follow the link for full your requirement:



          Custom AJAX discount-form not processing coupons



          lelandcope






          share|improve this answer


























          • Thanks.. I followed the same tutorial but it is not working.. coupon code is also not working nor ajax..It is giving me "error message"

            – Shoeb Mirza
            Jun 30 '15 at 21:02



















          0














          I have created one module for discount code popup which has method to apply code without reloading cart page



          Here is link for this module for reference



          in your javascript method updateCoupon() you have call ajax method which calls controller action in that you need to add following code to apply code without refreshing page Here applyAction is my ajax action



          public function applyAction()
          {
          $response = array();
          $couponCode = (string) $this->getRequest()->getParam('coupon_code');
          if ($this->getRequest()->getParam('remove') == 1) {
          $couponCode = '';
          }
          $oldCouponCode = $this->_getQuote()->getCouponCode();
          if (!strlen($couponCode) && !strlen($oldCouponCode)) {
          $message = "Please enter valid code";
          $response['error'] = 1;
          }
          try {
          $codeLength = strlen($couponCode);
          $isCodeLengthValid = $codeLength && $codeLength <= Mage_Checkout_Helper_Cart::COUPON_CODE_MAX_LENGTH;
          $this->_getQuote()->getShippingAddress()->setCollectShippingRates(true);
          $this->_getQuote()->setCouponCode($isCodeLengthValid ? $couponCode : '')
          ->collectTotals()
          ->save();
          if ($codeLength) {
          if ($isCodeLengthValid && $couponCode == $this->_getQuote()->getCouponCode()) {
          $message = $this->__('Coupon code "%s" was applied.', Mage::helper('core')->escapeHtml($couponCode));
          $this->_getSession()->setCartCouponCode($couponCode);
          } else {
          $message = $this->__('Coupon code "%s" is not valid.', Mage::helper('core')->escapeHtml($couponCode));
          $response['error'] = 1;
          }
          } else {
          $message = $this->__('Coupon code was canceled.');
          }
          } catch (Mage_Core_Exception $e) {
          $message = $e->getMessage();
          $response['error'] = 1;
          } catch (Exception $e) {
          $response['error'] = 1;
          $message = $this->__('Cannot apply the coupon code.');
          Mage::logException($e);
          }
          $response['message'] = $message;
          $response['code'] = $couponCode;
          $this->getResponse()->setBody(Mage::helper('core')->jsonEncode($response));
          }





          share|improve this answer


























            Your Answer








            StackExchange.ready(function() {
            var channelOptions = {
            tags: "".split(" "),
            id: "479"
            };
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function() {
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled) {
            StackExchange.using("snippets", function() {
            createEditor();
            });
            }
            else {
            createEditor();
            }
            });

            function createEditor() {
            StackExchange.prepareEditor({
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: false,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: null,
            bindNavPrevention: true,
            postfix: "",
            imageUploader: {
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            },
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            });


            }
            });














            draft saved

            draft discarded


















            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fmagento.stackexchange.com%2fquestions%2f72629%2fapply-magento-coupon-in-ajax-without-redirecting-to-cart-page%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown

























            2 Answers
            2






            active

            oldest

            votes








            2 Answers
            2






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            0














            There are lot issue in your code.



            JavaScript is wrong.you have call opcheckout.js function payment.payment.onSave and checkout.ajaxFailure.bind(checkout), etc which does not work on all pages.



            So you need to Custom code which will apply coupon code on ajax on all pages



            You can follow the link for full your requirement:



            Custom AJAX discount-form not processing coupons



            lelandcope






            share|improve this answer


























            • Thanks.. I followed the same tutorial but it is not working.. coupon code is also not working nor ajax..It is giving me "error message"

              – Shoeb Mirza
              Jun 30 '15 at 21:02
















            0














            There are lot issue in your code.



            JavaScript is wrong.you have call opcheckout.js function payment.payment.onSave and checkout.ajaxFailure.bind(checkout), etc which does not work on all pages.



            So you need to Custom code which will apply coupon code on ajax on all pages



            You can follow the link for full your requirement:



            Custom AJAX discount-form not processing coupons



            lelandcope






            share|improve this answer


























            • Thanks.. I followed the same tutorial but it is not working.. coupon code is also not working nor ajax..It is giving me "error message"

              – Shoeb Mirza
              Jun 30 '15 at 21:02














            0












            0








            0







            There are lot issue in your code.



            JavaScript is wrong.you have call opcheckout.js function payment.payment.onSave and checkout.ajaxFailure.bind(checkout), etc which does not work on all pages.



            So you need to Custom code which will apply coupon code on ajax on all pages



            You can follow the link for full your requirement:



            Custom AJAX discount-form not processing coupons



            lelandcope






            share|improve this answer















            There are lot issue in your code.



            JavaScript is wrong.you have call opcheckout.js function payment.payment.onSave and checkout.ajaxFailure.bind(checkout), etc which does not work on all pages.



            So you need to Custom code which will apply coupon code on ajax on all pages



            You can follow the link for full your requirement:



            Custom AJAX discount-form not processing coupons



            lelandcope







            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited Apr 13 '17 at 12:54









            Community

            1




            1










            answered Jun 30 '15 at 12:14









            Amit BeraAmit Bera

            60.2k1678178




            60.2k1678178













            • Thanks.. I followed the same tutorial but it is not working.. coupon code is also not working nor ajax..It is giving me "error message"

              – Shoeb Mirza
              Jun 30 '15 at 21:02



















            • Thanks.. I followed the same tutorial but it is not working.. coupon code is also not working nor ajax..It is giving me "error message"

              – Shoeb Mirza
              Jun 30 '15 at 21:02

















            Thanks.. I followed the same tutorial but it is not working.. coupon code is also not working nor ajax..It is giving me "error message"

            – Shoeb Mirza
            Jun 30 '15 at 21:02





            Thanks.. I followed the same tutorial but it is not working.. coupon code is also not working nor ajax..It is giving me "error message"

            – Shoeb Mirza
            Jun 30 '15 at 21:02













            0














            I have created one module for discount code popup which has method to apply code without reloading cart page



            Here is link for this module for reference



            in your javascript method updateCoupon() you have call ajax method which calls controller action in that you need to add following code to apply code without refreshing page Here applyAction is my ajax action



            public function applyAction()
            {
            $response = array();
            $couponCode = (string) $this->getRequest()->getParam('coupon_code');
            if ($this->getRequest()->getParam('remove') == 1) {
            $couponCode = '';
            }
            $oldCouponCode = $this->_getQuote()->getCouponCode();
            if (!strlen($couponCode) && !strlen($oldCouponCode)) {
            $message = "Please enter valid code";
            $response['error'] = 1;
            }
            try {
            $codeLength = strlen($couponCode);
            $isCodeLengthValid = $codeLength && $codeLength <= Mage_Checkout_Helper_Cart::COUPON_CODE_MAX_LENGTH;
            $this->_getQuote()->getShippingAddress()->setCollectShippingRates(true);
            $this->_getQuote()->setCouponCode($isCodeLengthValid ? $couponCode : '')
            ->collectTotals()
            ->save();
            if ($codeLength) {
            if ($isCodeLengthValid && $couponCode == $this->_getQuote()->getCouponCode()) {
            $message = $this->__('Coupon code "%s" was applied.', Mage::helper('core')->escapeHtml($couponCode));
            $this->_getSession()->setCartCouponCode($couponCode);
            } else {
            $message = $this->__('Coupon code "%s" is not valid.', Mage::helper('core')->escapeHtml($couponCode));
            $response['error'] = 1;
            }
            } else {
            $message = $this->__('Coupon code was canceled.');
            }
            } catch (Mage_Core_Exception $e) {
            $message = $e->getMessage();
            $response['error'] = 1;
            } catch (Exception $e) {
            $response['error'] = 1;
            $message = $this->__('Cannot apply the coupon code.');
            Mage::logException($e);
            }
            $response['message'] = $message;
            $response['code'] = $couponCode;
            $this->getResponse()->setBody(Mage::helper('core')->jsonEncode($response));
            }





            share|improve this answer






























              0














              I have created one module for discount code popup which has method to apply code without reloading cart page



              Here is link for this module for reference



              in your javascript method updateCoupon() you have call ajax method which calls controller action in that you need to add following code to apply code without refreshing page Here applyAction is my ajax action



              public function applyAction()
              {
              $response = array();
              $couponCode = (string) $this->getRequest()->getParam('coupon_code');
              if ($this->getRequest()->getParam('remove') == 1) {
              $couponCode = '';
              }
              $oldCouponCode = $this->_getQuote()->getCouponCode();
              if (!strlen($couponCode) && !strlen($oldCouponCode)) {
              $message = "Please enter valid code";
              $response['error'] = 1;
              }
              try {
              $codeLength = strlen($couponCode);
              $isCodeLengthValid = $codeLength && $codeLength <= Mage_Checkout_Helper_Cart::COUPON_CODE_MAX_LENGTH;
              $this->_getQuote()->getShippingAddress()->setCollectShippingRates(true);
              $this->_getQuote()->setCouponCode($isCodeLengthValid ? $couponCode : '')
              ->collectTotals()
              ->save();
              if ($codeLength) {
              if ($isCodeLengthValid && $couponCode == $this->_getQuote()->getCouponCode()) {
              $message = $this->__('Coupon code "%s" was applied.', Mage::helper('core')->escapeHtml($couponCode));
              $this->_getSession()->setCartCouponCode($couponCode);
              } else {
              $message = $this->__('Coupon code "%s" is not valid.', Mage::helper('core')->escapeHtml($couponCode));
              $response['error'] = 1;
              }
              } else {
              $message = $this->__('Coupon code was canceled.');
              }
              } catch (Mage_Core_Exception $e) {
              $message = $e->getMessage();
              $response['error'] = 1;
              } catch (Exception $e) {
              $response['error'] = 1;
              $message = $this->__('Cannot apply the coupon code.');
              Mage::logException($e);
              }
              $response['message'] = $message;
              $response['code'] = $couponCode;
              $this->getResponse()->setBody(Mage::helper('core')->jsonEncode($response));
              }





              share|improve this answer




























                0












                0








                0







                I have created one module for discount code popup which has method to apply code without reloading cart page



                Here is link for this module for reference



                in your javascript method updateCoupon() you have call ajax method which calls controller action in that you need to add following code to apply code without refreshing page Here applyAction is my ajax action



                public function applyAction()
                {
                $response = array();
                $couponCode = (string) $this->getRequest()->getParam('coupon_code');
                if ($this->getRequest()->getParam('remove') == 1) {
                $couponCode = '';
                }
                $oldCouponCode = $this->_getQuote()->getCouponCode();
                if (!strlen($couponCode) && !strlen($oldCouponCode)) {
                $message = "Please enter valid code";
                $response['error'] = 1;
                }
                try {
                $codeLength = strlen($couponCode);
                $isCodeLengthValid = $codeLength && $codeLength <= Mage_Checkout_Helper_Cart::COUPON_CODE_MAX_LENGTH;
                $this->_getQuote()->getShippingAddress()->setCollectShippingRates(true);
                $this->_getQuote()->setCouponCode($isCodeLengthValid ? $couponCode : '')
                ->collectTotals()
                ->save();
                if ($codeLength) {
                if ($isCodeLengthValid && $couponCode == $this->_getQuote()->getCouponCode()) {
                $message = $this->__('Coupon code "%s" was applied.', Mage::helper('core')->escapeHtml($couponCode));
                $this->_getSession()->setCartCouponCode($couponCode);
                } else {
                $message = $this->__('Coupon code "%s" is not valid.', Mage::helper('core')->escapeHtml($couponCode));
                $response['error'] = 1;
                }
                } else {
                $message = $this->__('Coupon code was canceled.');
                }
                } catch (Mage_Core_Exception $e) {
                $message = $e->getMessage();
                $response['error'] = 1;
                } catch (Exception $e) {
                $response['error'] = 1;
                $message = $this->__('Cannot apply the coupon code.');
                Mage::logException($e);
                }
                $response['message'] = $message;
                $response['code'] = $couponCode;
                $this->getResponse()->setBody(Mage::helper('core')->jsonEncode($response));
                }





                share|improve this answer















                I have created one module for discount code popup which has method to apply code without reloading cart page



                Here is link for this module for reference



                in your javascript method updateCoupon() you have call ajax method which calls controller action in that you need to add following code to apply code without refreshing page Here applyAction is my ajax action



                public function applyAction()
                {
                $response = array();
                $couponCode = (string) $this->getRequest()->getParam('coupon_code');
                if ($this->getRequest()->getParam('remove') == 1) {
                $couponCode = '';
                }
                $oldCouponCode = $this->_getQuote()->getCouponCode();
                if (!strlen($couponCode) && !strlen($oldCouponCode)) {
                $message = "Please enter valid code";
                $response['error'] = 1;
                }
                try {
                $codeLength = strlen($couponCode);
                $isCodeLengthValid = $codeLength && $codeLength <= Mage_Checkout_Helper_Cart::COUPON_CODE_MAX_LENGTH;
                $this->_getQuote()->getShippingAddress()->setCollectShippingRates(true);
                $this->_getQuote()->setCouponCode($isCodeLengthValid ? $couponCode : '')
                ->collectTotals()
                ->save();
                if ($codeLength) {
                if ($isCodeLengthValid && $couponCode == $this->_getQuote()->getCouponCode()) {
                $message = $this->__('Coupon code "%s" was applied.', Mage::helper('core')->escapeHtml($couponCode));
                $this->_getSession()->setCartCouponCode($couponCode);
                } else {
                $message = $this->__('Coupon code "%s" is not valid.', Mage::helper('core')->escapeHtml($couponCode));
                $response['error'] = 1;
                }
                } else {
                $message = $this->__('Coupon code was canceled.');
                }
                } catch (Mage_Core_Exception $e) {
                $message = $e->getMessage();
                $response['error'] = 1;
                } catch (Exception $e) {
                $response['error'] = 1;
                $message = $this->__('Cannot apply the coupon code.');
                Mage::logException($e);
                }
                $response['message'] = $message;
                $response['code'] = $couponCode;
                $this->getResponse()->setBody(Mage::helper('core')->jsonEncode($response));
                }






                share|improve this answer














                share|improve this answer



                share|improve this answer








                edited Jan 23 '18 at 6:39









                Jaimin

                1,156729




                1,156729










                answered May 11 '17 at 11:05









                Vaibhav AhalparaVaibhav Ahalpara

                3,67542762




                3,67542762






























                    draft saved

                    draft discarded




















































                    Thanks for contributing an answer to Magento Stack Exchange!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid



                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.


                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function () {
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fmagento.stackexchange.com%2fquestions%2f72629%2fapply-magento-coupon-in-ajax-without-redirecting-to-cart-page%23new-answer', 'question_page');
                    }
                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    Popular posts from this blog

                    “%fieldName is a required field.”, in Magento2 REST API Call for GET Method Type The Next...

                    How to change City field to a dropdown in Checkout step Magento 2Magento 2 : How to change UI field(s)...

                    變成蝙蝠會怎樣? 參考資料 外部連結 导航菜单Thomas Nagel, "What is it like to be a...