I've got controller that render products in .phtml with add to cart button and return it via layout to ajax. When i hit the add to cart button this makes redirect to controller page. I need to reload current page or add the product via aja. btw i know why this happen, but don't how to fix this. any ideas? thanks!
1 Answer
In this file
vendor/magento/module-checkout/Controller/Cart/Add.php (where product is added to cart), magento calls
return $this->goBack($url);
which checks whether this request is ajax or not. If its ajax, it sends back a JSON instead of redirecting to a page.
see:
protected function goBack($backUrl = null, $product = null)
{
if (!$this->getRequest()->isAjax()) {
return parent::_goBack($backUrl);
}
$result = [];
if ($backUrl || $backUrl = $this->getBackUrl()) {
$result['backUrl'] = $backUrl;
} else {
if ($product && !$product->getIsSalable()) {
$result['product'] = [
'statusText' => __('Out of stock')
];
}
}
$this->getResponse()->representJson(
$this->_objectManager->get(\Magento\Framework\Json\Helper\Data::class)->jsonEncode($result)
);
}
Basically you need to pass 'ajax=true' in your add to cart request.
Hope this helps somehow.
-
Thanks for join, but i found another solution by passing current url to ajax and creating custom url generation. Anyway - thank you!Kharidas Chebotaryov– Kharidas Chebotaryov2018-11-05 13:04:38 +00:00Commented Nov 5, 2018 at 13:04