Tuesday, 19 March 2013

Add Related Product using Ajax

<script src="<?php echo $this->getJsUrl() ?>mage/adminhtml/loader.js" type="text/javascript"></script>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script>var js = jQuery.noConflict(); </script>
<?php if($this->getItems()->getSize()): ?>
      
      <form action="" method="post" id="" enctype="multipart/form-data">
           <input type="hidden" name="related_product_custom" id="related_product_custom" value="" />
        <ol class="relatedeasy">
        <?php foreach($this->getItems() as $_item): ?>
        <li class="relatedli<?php if($_item->isComposite() || !$_item->isSaleable()): ?>&nbsp;super-products<?php endif; ?>">
            <div class="product-images">
            <?php if(!$_item->isComposite() && $_item->isSaleable()): ?>
                <span class="checkbox-container">
                <?php if (!$_item->getRequiredOptions()): ?>
                   
                    <input name="qty_related_<?php echo $_item->getId() ?>" id="qty_related_<?php echo $_item->getId() ?>" value="" size="4" title="<?php echo $this->__('Qty') ?>" class="input-text qty rel_qty" maxlength="12" />
                <?php endif; ?>
                </span>
            <?php else: ?>
                <span class="checkbox-container">&nbsp;</span>
            <?php endif; ?>
                <a href="<?php echo $_item->getProductUrl() ?>"><img src="<?php echo $this->helper('catalog/image')->init($_item, 'thumbnail')->resize(56) ?>" alt="<?php echo $this->htmlEscape($_item->getName()) ?>" /></a>
            </div>
            <div class="product-details">
                    <div class="shortdesc"><a href="<?php echo $_item->getProductUrl() ?>"><?php echo $this->htmlEscape($_item->getName()) ?></a>
                   <?php echo $_item->getShortDescription()?>
                    </div>
                    <?php echo $this->getPriceHtml($_item, true) ?>
                   
            </div>
        </li>
        <?php endforeach ?>
        <button type="button" title="<?php echo $this->__('Add to Cart') ?>" id="cart_add"  class="button btn-cart" ><span><span><?php echo $this->__('Add to Cart') ?></span></span></button>
        <div id="loadingmask" style="display: none;">
<div class="loader" id="loading-mask-loader"><img src="<?php echo str_replace("index.php/","",$this->getUrl()) ?>skin/adminhtml/default/default/images/ajax-loader-tr.gif" alt="<?php echo $this->__('Loading...') ?>"/><?php echo $this->__('Loading...') ?></div>
<div id="loading-mask"></div>
</div>
        </ol>
        </form>
<script type="text/javascript"> 

  js(document).ready(function() {
    js('#cart_add').live('click', function(event)
 {

    var pdt_arr=[];
   
   js('.rel_qty').each(function(e,elem){
       
        var pdt_id=elem.readAttribute('id').split('_')[2];
        var qty=js('#qty_related_'+pdt_id).val();
           var str="";
        if(qty>0)
        {
            var pdt_qty=pdt_id+"_"+qty;
    
            pdt_arr.push(pdt_qty);
        }       
    });
   
      js('#related_product_custom').val(pdt_arr);
     var myval=    js('#related_product_custom').val();
    Element.show('loadingmask');
    js.ajax({
        type: "POST",
        url: "<?php echo $this->getUrl('checkout/cart/addnew') ?>",
        cache: false,
        data: "pdt="+myval,
        success: function(data)
        {
            Element.hide('loadingmask');
            location.reload();           
            alert("Product added Successfully");
          
        }
         });

 });
 });
 </script>
<?php endif ?>


Add function in Controller /app/code/core/Mage/Checkout/controllers/cartcontroller

public function addnewAction()
    {
            try
            {
             $params = $this->getRequest()->getParams('pdt'); 
             $pqty=explode(",",$params['pdt']);         
             $cart = Mage::getSingleton('checkout/cart');
             $model = Mage::getModel('catalog/product');       
            //print_r(explode("_",$pqty[0]));
              for($i=0;$i<count($pqty);$i++)
                {
                                   
                     $qty=explode("_",$pqty[$i]);
                                              
                     $_product = $model->load($qty[0]);
                    // $_product->setVisibility(Mage_Catalog_Model_Product_Visibility::VISIBILITY_BOTH); 
                    //print_r($_product->getId());             
                     $cart->addProduct($_product->getId(), $qty[1]);
                   
               }
               $cart->save();
              Mage::getSingleton('checkout/session')->setCartWasUpdated(true);
                  
          
        }
        catch(exception $e){

                return $e->getMessage().$e->getLine();
        }
    }

2 comments:

  1. Great article, it was very helpful! I just started in this and I'm getting to know it better! Cheers, keep up the good work!

    Magento Singapore

    ReplyDelete