July 22, 2015

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>

0 comments:

Post a Comment