miao miao - 1 month ago 6
Ajax Question

How to refresh content of page after adding item with AJAX

I have some url which i add some item to another page (cart page) but by refreshing page and it works fine, now i tried to do it with Ajax, so i created an ajax function to call this URL it works and it adds my item.

Now the problem is i have to reload the other page (cart page) to see the product. So how to do to refresh this page after adding the item, i mean after calling this URL.

The Url :

<?php echo Mage::helper('checkout/cart')->getAddUrl($_product, $params); ?>


cart.phtml


...
<div class="row">
<div class="col-md-6">
<div class="product-qty">
<div class="custom-qty">
<div class="btn-plus">
<button type="button" class="reduced items" onclick="minusQty('<?php echo $_product->getId() ?>')">
<i class="fa fa-minus"></i>
</button>
<input name="qty" id="qty-<?php echo $_product->getId()?>" maxlength="12" value="1" title="Qté" class="input-text qty" type="text">
<button type="button" class="increase items" onclick="plusQty('<?php echo $_product->getId() ?>')">
<i class="fa fa-plus"></i>
</button>
</div>
</div>
</div>
</div>
<?php $params = array('qty'=>2) // the input value ?>
<div class="col-md-6">
<button type="button" title="<?php echo $this->__('Add') ?>" class="button btn-cart pull-left-none" onclick="addToCartAjax('<?php echo Mage::helper('checkout/cart')->getAddUrl($_product, $params); ?>')" >
<span><span><?php echo $this->__('Add') ?></span></span>
</button>
</div>
</div>

//JS PART
<script type="text/javascript">
function addToCartAjax(addUrl) {
jQuery.ajax ({
url: addUrl,
type : 'GET',
})
}
</script>


EDIT:

Content of
cart.phtml


<div class="row">
<div class="col-main col-lg-12">
<div class="cart">
<fieldset>
...
<tbody>
<tr class="first odd"><td>Item1</td></tr>
<tr class="last even"><td>Item2</td></tr>
</tbody>
...
</fieldset>
</div>
</div>
</div>


EDIT2:

Action controller

public function addAction()
{

if (!$this->_validateFormKey()) {
$this->_goBack();
return;
}
$cart = $this->_getCart();
$params = $this->getRequest()->getParams();
try {
if (isset($params['qty'])) {
$filter = new Zend_Filter_LocalizedToNormalized(
array('locale' => Mage::app()->getLocale()->getLocaleCode())
);
$params['qty'] = $filter->filter($params['qty']);
}

$product = $this->_initProduct();
$related = $this->getRequest()->getParam('related_product');

/**
* Check product availability
*/
if (!$product) {
$this->_goBack();
return;
}

$cart->addProduct($product, $params);
if (!empty($related)) {
$cart->addProductsByIds(explode(',', $related));
}

$cart->save();

$this->_getSession()->setCartWasUpdated(true);

/**
* @todo remove wishlist observer processAddToCart
*/
Mage::dispatchEvent('checkout_cart_add_product_complete',
array('product' => $product, 'request' => $this->getRequest(), 'response' => $this->getResponse())
);

if (!$this->_getSession()->getNoCartRedirect(true)) {
if (!$cart->getQuote()->getHasError()) {
$message = $this->__('%s was added to your shopping cart.', Mage::helper('core')->escapeHtml($product->getName()));
$this->_getSession()->addSuccess($message);
}
$this->_goBack();
}
} catch (Mage_Core_Exception $e) {
if ($this->_getSession()->getUseNotice(true)) {
$this->_getSession()->addNotice(Mage::helper('core')->escapeHtml($e->getMessage()));
} else {
$messages = array_unique(explode("\n", $e->getMessage()));
foreach ($messages as $message) {
$this->_getSession()->addError(Mage::helper('core')->escapeHtml($message));
}
}

$url = $this->_getSession()->getRedirectUrl(true);
if ($url) {
$this->getResponse()->setRedirect($url);
} else {
$this->_redirectReferer(Mage::helper('checkout/cart')->getCartUrl());
}
} catch (Exception $e) {
$this->_getSession()->addException($e, $this->__('Cannot add the item to shopping cart.'));
Mage::logException($e);
$this->_goBack();
}
}

Answer Source

I assume when you add an item to the cart you get some kind of response from your server about current items of the cart, if not you have to implement that on the server side first

  1. add this to your function :

      function addToCartAjax(addUrl){
        $.ajax({
          url: addUrl,
          type: 'GET',
    
         })
         .done(function(response ) {
             //response - this is the response from the server
         });
     }
    
  2. I don't know exactly what your server returns if it is html than in .done closure do this :

      .done(function(response ) {
           // response - this is the response from the server
           $('.YourCartContainer').html(response);
       });
    

    so if your server returns an html snippet that contains your cart items than you should insert in as html into your cart div container , but if the server returns a Json response with items than you have to loop through them with jquery and format appropriately here an example , however again I don't know what your server returns so just apply the technique :

      .done(function(response ) {
           // response - this is the response from the server
           var htmlResult = '';
           $.each(response, function( item ) {
              htmlResult += '<p>'+ item.name + '</p><br>'
           });
          $('.YourCartContainer').html(htmlResult);
       });
    

    So here I looped through the json and created some simple html where you get all the item names that are inside the cart, hope this helped ! if You need more info regarding your case specifically than please post what your server response looks like !!