Magento – Ajax Add to Cart from Product Page Using jQuery

In this article, we are going to discuss about How to create an Ajax based Add to Cart from Product Page Using jQuery in Magento. This is just going to be a quick snippet. One thing I get asked a lot is how to add a product to the cart using ajax and its actually quite easy to do. Now I'm not going to go over how to use jQuery with Magento because there are plenty of tutorials on how to do that. I am going to assume you have jQuery setup in Magento.

<script type="text/javascript"> 
  (function($) 
  { 
    $(document).ready(function() 
    { 
      // Setup the click event 
      $('#product_addtocart_form').submit(addToCart); 
       
    }); 
     
    function addToCart(e) 
    { 
      e.preventDefault(); 
       
      // Here You Should Validate Your Information.  
      // For example if you have options that need to be selected like shirt size 
       
      // Now get the forms data 
      var formData = $('#product_addtocart_form').serialize(); 

      // Now because we are adding the cart through ajax you need to add this so the controller knows that it is ajax and can pass back json if there is an error 
      formData += '&isAjax=1'; 
       
      // Send the form data over 
      $.ajax({ 
        url:$('#product_addtocart_form').attr('action'), 
        type:'POST', 
        data:formData, 
        dataType:'json', 
        success:function(data) 
        { 
          // Do what you want. You have added a product to your cart 
          // I Like to show my persistant cart popup here 
        } 
      }); 
    } 
       
  })(jQuery); 

</script>

Create an Ajax Coupon / Discount Code Box in Magento

In this article, we are going to discuss about How to create an Ajax Coupon / Discount code box in Magento. Basically this will set you up with the new extension you are going to create. The only thing in the tutorial that you do not need to do is putting any information in the controller file. I am going to assume you have followed the tutorial and you are ready to edit your CartController.php. To start off your file is going to look like this.

<?php 
require_once 'Mage/Checkout/controllers/CartController.php'; 
class YourNameSpace_YourModule_CartController extends Mage_Checkout_CartController 


}

This is our basic controller file. With this any functions we write that have the same name as the Mage Cart Controller will now be overwritten. this is great if you ever need to make changes like adding ajax functionality to any other parts of magento. Next we add the following code and our file should look like this.

<?php 
require_once 'Mage/Checkout/controllers/CartController.php'; 

class YourNameSpace_YourModule_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; 

}

So basically what we do is check for a POST variable called ajax. If this does not exist then we know not to use our ajax code so let the regular code run or the parents code if you will. If it is available then we continue. The code is essentially the same as it's parent except instead of putting any errors into a session variable and send the browser back a page, we are echoing out any error messages. If the $msg variable is empty then we know there were no errors.

Now we can move on to our form and javascript. Our form should look something like the following

<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>

This is just your basic discount code form. You can make any design modifications as you want the only things that are important are the form tags and the input box. Once you have your form you will want to create the following javascript

$('#discountcode-form').submit(function(e) 

  e.preventDefault(); 
   
  $.ajax({ 
    url:$('#discountcode-form').attr('action'), 
    type:'POST', 
    data:'ajax=true&'+$('#discountcode-form').serialize(), 
    success:function(data) 
    { 
      if(data != '') 
      { 
        // Display error message however you would like 
      } 
    } 
  }); 
});

What this script does is takes the action url from the form and passes all of the forms data to our php script using the jQuery ajax function. It then listens for a response. If it getts something other then null you can take that message and display it however you like.

If you have any questions please let me know and as always leave your feedback...