Magento ajax添加到购物车产品未找到错误

时间:2013-11-28 07:37:19

标签: php jquery ajax magento

magento 1.8 ajax购物车显示未找到产品错误

我使用的java脚本是

    function setLocationAjax(url,id){
        var data = jQuery('#product_addtocart_form').serialize();
        data += '&isAjax=1'; 
        url = url.replace("checkout/cart","ajax/index");
        jQuery('#ajax_loader'+id).show();
        try {
            jQuery.ajax( {
                url : url,
                dataType : 'json',
                type : 'post',
                data: data,
                success : function(data) {
                    jQuery('#ajax_loader'+id).hide();
                    setAjaxData(data,false);          
                }
            });
        } catch (e) {
        }
    }

function setAjaxData(data,iframe){

        if(data.status == 'ERROR'){
            alert(data.message);
        }else{
            if(jQuery('.block-cart')){
                jQuery('.block-cart').replaceWith(data.sidebar);
            }
//            if(jQuery('.header .links')){
//                jQuery('.header .links').replaceWith(data.toplink);
//            }
            if(jQuery('.cart-top-container')){
                //jQuery('.cart-top-container').empty();
                jQuery('.cart-top-container').replaceWith(data.toplink);
            }
            var targetUrl='<?php echo Mage::getUrl('onestepcheckout') ?>';
            jQuery( "#dialog-confirm" ).dialog({
                resizable: false,
                height:140,
                modal: true,
                buttons: {
                    "Checkout": function() {
                        window.location.href = targetUrl;
                       jQuery(this).dialog( "close" );
                    },
                    "Continue Shopping": function() {
                        jQuery(this).dialog( "close" );
                    }
                }
            });
        }
    }

产品无法获取添加到购物车所需的产品信息。除了此代码之外,有没有办法将产品添加到购物车?

*表格是*

    <form action="<?php echo $this->getSubmitUrl($p) ?>" method="post" id="product_addtocart_form"<?php if ($p->getOptions()): ?> enctype="multipart/form-data"<?php endif; ?>>
                        <div class="home-prouduct-details">
                            <?php $pid = $p->getId(); ?>
                            <?php $prod = Mage::getModel('catalog/product')->load($pid);  ?>
                            <?php $html= $prod->getShortDescription(); ?>
                            <?php                          
                               $str = $html;
                               $matches = array();
                               preg_match_all('#<div[^>]*>(.*?)</div>#', $str, $matches);
//                               print_r($matches[1][0]);
                            ?>
                            <a class="prod-name" href="<?php echo $prod->getProductUrl(); ?>"><?php echo $prod->getName(); ?></a>
                            <div class="prod-img">
                                <a href="<?php echo $prod->getProductUrl() ?>" title="<?php echo $this->stripTags($this->getImageLabel($prod, 'small_image'), null, true) ?>" class="product-image">
                                    <img src="<?php echo $this->helper('catalog/image')->init($prod, 'small_image')->resize(285,172); ?>" width="285" height="175" alt="<?php echo $this->stripTags($this->getImageLabel($prod, 'small_image'), null, true) ?>" />
                                </a>
                            </div>
                            <div class="home-price-button">
                                <?php $almost_gone_qty=$this->htmlEscape($prod->getData('almost_gone_qty')); ?>
                                <?php $qtyStock = Mage::getModel('cataloginventory/stock_item')->loadByProduct($prod)->getQty(); ?>
                                <?php if (!$this->hasOptions() && strtotime($prod->getDealEndDate())>= Mage::getModel('core/date')->timestamp(time())):?>
                                    <div style="clear:both;"></div>
                                    <div class="add-to-box">
                                        <?php if($prod->isSaleable() && $qtyStock > $almost_gone_qty){ ?>
                                            <p class="availability out-of-stock">
                                                <a onclick="setLocationAjax('/checkout/cart/add/product/<?php echo $prod; ?>',<?php echo $prod->getId();?>)" title="Add To Cart">
                                                    <img src="<?php echo $this->getSkinUrl('images/steamy.png'); ?>" title="Add To Cart" alt="Add To Cart" width="285" />
                                                </a>
                                            </p>
                                            <?php } else if($qtyStock <= $almost_gone_qty && $qtyStock!=0){?>
                                                <p class="availability out-of-stock">
                                                    <a onclick="setLocationAjax('/checkout/cart/add/product/?<?php echo $prod; ?>',<?php echo $prod->getId();?>)" title="Almost Gone">
                                                        <img src="<?php echo $this->getSkinUrl('images/almostgone.png'); ?>" title="Almost Gone" alt="Almost Gone" width="285" />
                                                    </a>
                                                </p>
                                            <?php } else{ ?>
                                                <p class="availability out-of-stock">
                                                    <a href="<?php echo Mage::getBaseUrl(); ?>sold-out" title="Sold Out">
                                                        <img src="<?php echo $this->getSkinUrl('images/soldout.png'); ?>" width="285" /><?php //echo $this->__('Out of stock') ?>
                                                    </a>
                                                </p>
                                            <?php } ?>
                                            <span id='ajax_loader<?php echo $prod->getId()?>' style='text-align: center; display:none'><img src='<?php echo $this->getSkinUrl('images/opc-ajax-loader.gif')?>'/></span>
                                    </div>                                    
                                <?php else : ?>
                                    <p class="deal-has-ended">
                                        <a href="<?php echo Mage::getBaseUrl(); ?>sold-out" title="Sold Out">
                                            <img src="<?php echo $this->getSkinUrl('images/deal_ended.png'); ?>" width="285" />
                                        </a>
                                    </p>                                
                                <?php endif; ?>
                                    <?php //echo $this->getChildHtml('addto') ?>
                                    <?php //echo $this->getChildHtml('extra_buttons') ?>
                            </div>
                            <div class="home-price">
                                <div class="home-prices">
                                    <?php 
                                        echo Mage::helper('core')->currency($prod->getPrice());
                                    ?>    
                                </div>
                                <?php if($matches[1][1] !=""){ ?>
                                    <div class="home-save">
                                        <?php
                                            $savings = $matches[1][1];
                                            $savings = str_ireplace('Rs.', '&#8377;', $savings);
                                            $savings = str_ireplace('Rs', '&#8377;', $savings);
                                            echo $savings;
                                        ?>
                                        <?php //print_r($matches[1][1]); ?>
                                        <div class="home-saver">
                                            savings
                                        </div>
                                    </div>
                                <?php } ?>
                                <div class="deal-endtime"> 
                                    <?php 
                                                    echo "<div id='cdcontainer_".$prod->getId()."' class='cdcontainer'></div>";
                                                    $dealEndDate = $prod->getDealEndDate();
                                                    $dealEndDateParts = explode(" ", $dealEndDate);
                                                    $targetDateParts = explode("-", $dealEndDateParts[0]);
                                                    $year = $targetDateParts[0];
                                                    $month = $targetDateParts[1];
                                                    $date = $targetDateParts[2];

                                                    $month_array = array(
                                                            "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"
                                                    );
                                                    $month = $month_array[$month-1];

                                                    $targetDate = "$month $date, $year ".$dealEndDateParts[1];
                                                    $timer_text = Mage::getStoreConfig('homedeals/basic_settings/cd_display_text');
                                                    $timer_end_text = Mage::getStoreConfig('homedeals/basic_settings/cd_end_text');     
                                                    //echo $timer_end_text;
                                                    //echo date("Y-m-d H:i:s"); echo "<br/>";
                                                    //echo $dealEndDate;
                                                    if($dealEndDate <= date("Y-m-d H:i:s")){
                                                    ?>
                                                    <script type="text/javascript">
                                                            var launchdate_<?php echo $prod->getId(); ?>=new cdLocalTime("cdcontainer_<?php echo $_product->getId(); ?>", "server-php", 0, "", "", "<?php echo '<span><h1 style=color:red;>Deal has ended - 00:00:00</h1></span>' ?><?php //echo $timer_text; ?>", "<?php echo $timer_end_text; ?>", "<?php echo $prod->getId(); ?>");
                                                            launchdate_<?php echo $prod->getId(); ?>.displaycountdown("hours", formatresults2);
                                                    </script>
                                                    <?php   }else { ?>
                                                    <script type="text/javascript">
                                                            var launchdate_<?php echo $prod->getId(); ?>=new cdLocalTime("cdcontainer_<?php echo $prod->getId(); ?>", "server-php", 0, "<?php echo $targetDate?>", "<?php print date("F d, Y H:i:s", Mage::getModel('core/date')->timestamp(time()))?>", "<?php echo $timer_text; ?>", "<?php echo $timer_end_text; ?>", "<?php echo $prod->getId(); ?>");

                                                            launchdate_<?php echo $prod->getId(); ?>.displaycountdown("hours", formatresults2);
                                                    </script>
                                                    <?php } ?>
                                </div>
                            </div>
                        </div>
                        <div id="dialog-confirm" style="display:none;">
                            <?php echo $prod->getName();?> added to your cart Successfully.
                        </div>
                        </form>

我猜还有一个网址问题提前致谢。

我的控制器代码是

 protected function _getProduct($productInfo)
    {
        $product = null;
        if ($productInfo instanceof Mage_Catalog_Model_Product) {
            $product = $productInfo;
        } elseif (is_int($productInfo) || is_string($productInfo)) {
            $product = Mage::getModel('catalog/product')
                ->setStoreId(Mage::app()->getStore()->getId())
                ->load($productInfo);
        }
        $currentWebsiteId = Mage::app()->getStore()->getWebsiteId();
        if (!$product
            || !$product->getId()
            || !is_array($product->getWebsiteIds())
            || !in_array($currentWebsiteId, $product->getWebsiteIds())
        ) {
            Mage::throwException(Mage::helper('checkout')->__('The product could not be found.'));
        }
        return $product;
    }

    /**
     * Get request for product add to cart procedure
     *
     * @param   mixed $requestInfo
     * @return  Varien_Object
     */
    protected function _getProductRequest($requestInfo)
    {
        if ($requestInfo instanceof Varien_Object) {
            $request = $requestInfo;
        } elseif (is_numeric($requestInfo)) {
            $request = new Varien_Object(array('qty' => $requestInfo));
        } else {
            $request = new Varien_Object($requestInfo);
        }

        if (!$request->hasQty()) {
            $request->setQty(1);
        }

        return $request;
    }

    /**
     * Add product to shopping cart (quote)
     *
     * @param   int|Mage_Catalog_Model_Product $productInfo
     * @param   mixed $requestInfo
     * @return  Mage_Checkout_Model_Cart
     */
    public function addProduct($productInfo, $requestInfo=null)
    {
        $product = $this->_getProduct($productInfo);
        $request = $this->_getProductRequest($requestInfo);

        $productId = $product->getId();

        if ($product->getStockItem()) {
            $minimumQty = $product->getStockItem()->getMinSaleQty();
            //If product was not found in cart and there is set minimal qty for it
            if ($minimumQty && $minimumQty > 0 && $request->getQty() < $minimumQty
                && !$this->getQuote()->hasProductId($productId)
            ){
                $request->setQty($minimumQty);
            }
        }

        if ($productId) {
            try {
                $result = $this->getQuote()->addProduct($product, $request);
            } catch (Mage_Core_Exception $e) {
                $this->getCheckoutSession()->setUseNotice(false);
                $result = $e->getMessage();
            }
            /**
             * String we can get if prepare process has error
             */
            if (is_string($result)) {
                $redirectUrl = ($product->hasOptionsValidationFail())
                    ? $product->getUrlModel()->getUrl(
                        $product,
                        array('_query' => array('startcustomization' => 1))
                    )
                    : $product->getProductUrl();
                $this->getCheckoutSession()->setRedirectUrl($redirectUrl);
                if ($this->getCheckoutSession()->getUseNotice() === null) {
                    $this->getCheckoutSession()->setUseNotice(true);
                }
                Mage::throwException($result);
            }
        } else {
            Mage::throwException(Mage::helper('checkout')->__('The product does not exist.'));
        }

        Mage::dispatchEvent('checkout_cart_product_add_after', array('quote_item' => $result, 'product' => $product));
        $this->getCheckoutSession()->setLastAddedProductId($productId);
        return $this;
    }

    /**
     * Adding products to cart by ids
     *
     * @param   array $productIds
     * @return  Mage_Checkout_Model_Cart
     */
    public function addProductsByIds($productIds)
    {
        $allAvailable = true;
        $allAdded     = true;

        if (!empty($productIds)) {
            foreach ($productIds as $productId) {
                $productId = (int) $productId;
                if (!$productId) {
                    continue;
                }
                $product = $this->_getProduct($productId);
                if ($product->getId() && $product->isVisibleInCatalog()) {
                    try {
                        $this->getQuote()->addProduct($product);
                    } catch (Exception $e){
                        $allAdded = false;
                    }
                } else {
                    $allAvailable = false;
                }
            }

            if (!$allAvailable) {
                $this->getCheckoutSession()->addError(
                    Mage::helper('checkout')->__('Some of the requested products are unavailable.')
                );
            }
            if (!$allAdded) {
                $this->getCheckoutSession()->addError(
                    Mage::helper('checkout')->__('Some of the requested products are not available in the desired quantity.')
                );
            }
        }
        return $this;
    }

1 个答案:

答案 0 :(得分:0)

您正在对没有任何输入元素的表单元素执行.serialize()。有一个注释http://api.jquery.com/serialize/关于哪些元素将使用函数序列化。

在setLocationAjax函数中,您将获得产品ID。只需将产品ID传递给php脚本即可。 即,

jQuery.ajax( {
            url : url,
            dataType : 'json',
            type : 'post',
            data: { productId: id },
            success : function(data) {
                jQuery('#ajax_loader'+id).hide();
                setAjaxData(data,false);          
            }
        });

在magento中,您可以根据productId获取产品并添加到购物车。