Magento 1.8 - AJAX POST后更新迷你购物车

时间:2016-09-05 10:49:11

标签: php ajax magento

在Magento的自定义页面上,我有一个简单的AJAX帖子,它将产品ID传递给php脚本:

jQuery.ajax({
  url: 'https://www.mywebsite.com/test/add_to_basket.php',
  type: "POST",
  data: data,
  success: function (data) {
  ,
  error: function (data) {
  }
});

这是add_to_basket php脚本:

$i = $_POST['i'];

require_once '../app/Mage.php';
umask(0);
Mage::app();

Mage::init('default');
Mage::getSingleton('core/session', array('name' => 'frontend'));  

$session = Mage::getSingleton('customer/session'); 

$cart = Mage::getSingleton('checkout/cart'); 
$cart->init();

$cart->addProduct($i, 1);

$session->setCartWasUpdated(true);

$cart->save(); 

这很有效,但迷你购物车不会更新。我已经读过我需要在etc / frontend中创建一个sections.xml文件,如下所示:

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Customer:etc/sections.xsd">
    <action name="[frontName]/[ActionPath]/[ActionName]">
        <section name="cart"/>
    </action>
</config>

但是我不确定[frontName] / [ActionPath] / [ActionName]在我的例子中会是什么。什么是最好的行动方案?

1 个答案:

答案 0 :(得分:0)

最重要的事情 - ajax.php:

require_once('/var/www/clients/client0/web1/web/app/Mage.php'); // ABSOLUTH PATH TO MAGE
umask(0);
Mage::app ();

Mage::getSingleton('core/session', array('name'=>'frontend'));   // GET THE SESSION

$simbol= Mage::app()->getLocale()->currency(Mage::app()->getStore()->getCurrentCurrencyCode())->getSymbol();  // GET THE CURRENCY SIMBOL
$store=Mage::app()->getStore()->getCode();  // GET THE STORE CODE

$cart = Mage::getSingleton('checkout/cart'); //->getItemsCount();   

$ajtem=$_POST['item'];    // THIS IS THE ITEM ID
$items = $cart->getItems();
foreach ($items as $item) {   // LOOP
   if($item->getId()==$ajtem){  // IS THIS THE ITEM WE ARE CHANGING? IF IT IS:
       $item->setQty($_POST['qty']); // UPDATE ONLY THE QTY, NOTHING ELSE!
       $cart->save();  // SAVE
       Mage::getSingleton('checkout/session')->setCartWasUpdated(true);
       echo '<span>';   
       if($store=='en')  echo $simbol;
       echo number_format($item->getPriceInclTax() * $_POST['qty'],2);
       if($store=='hr')  echo ' '.$simbol;
       echo '</span>';
       break;
   }

}

// THE REST IS updatTotalG FUNCTION WHICH IS CALLED AFTER AJAX IS COMPLETED 
// (UPDATE THE TOTALS)
echo '<script type="text/javascript">';
echo 'function updateTotalG(){';
echo 'jQuery("#sveUkupno").html(\'';
echo '<strong><span>';
//echo 'JQuery(\'#sveUkupno\').html("<strong><span>';
if($store=='en')  echo $simbol;
echo number_format(Mage::getSingleton('checkout/session')->getQuote()->getGrandTotal(),2);
//echo $simbol . ' </span></strong>");';
if($store=='hr')  echo ' '.$simbol;
echo " </span></strong>');";
echo '}   </script>';
  

您可以看到我们检测到脚本中的货币符号和   正在使用的商店。在它生成的脚本的末尾   我们用于列出购物车数量值的updateTotalG脚本。该   价值来自Magento。