0

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!

0

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 Nov 5 '18 at 13:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.