4

I have followed below & it works fine

Magento 2 : Add to Cart Button redirect to contact page

Only issue it should be redirected after product is added to cart.

I have tried different methods but seems not working http://devdocs.magento.com/guides/v2.0/extension-dev-guide/plugins.html

I tried using Observer but unable to redirect from Observer because of AJAX. It it's not AJAX then it works fine.

If somebody can guide how to redirect from Checkout page after product is added to cart. It would be better.

I'm using Porto Theme. So don't want to remove AJAX feature while Add to Cart

[UPDATE]

Through plugin I have achieved. Need to achieve something using Observer

public function afterExecute(\Magento\Checkout\Controller\Cart\Add $subject, $result) {
    $result = [];
    $result['backUrl'] = $this->url->getUrl('checkout');
    $subject->getResponse()->representJson($this->objectManager->get('Magento\Framework\Json\Helper\Data')->jsonEncode($result));
    return;
}
2

1 Answer 1

2

try this code.

use Magento\Framework\Event\ObserverInterface;

class TestObserver implements ObserverInterface
{
    protected $_responseFactory;
    protected $_url;

    public function __construct(\Magento\Framework\App\ResponseFactory $responseFactory,
\Magento\Framework\UrlInterface $url)
    {
        $this->_responseFactory = $responseFactory;
        $this->_url = $url;
    }

    public function execute(\Magento\Framework\Event\Observer $observer)
    {
        $cartUrl = $this->_url->getUrl('checkout/cart/index');
        $this->_responseFactory->create()->setRedirect($cartUrl)->sendResponse();            
        exit;
    }
}
5
  • can we redirect to checkout instead of cart/index/ ? Commented Jul 12, 2019 at 8:15
  • @jafarpinjar yes you can redirect on checkout page as well, into above code instade of cart page URL just pass the checkout page URL. Commented Jul 12, 2019 at 12:00
  • yes i used this there, $cartUrl = $this->_url->getUrl('checkout'), still it is redirected to checkout/cart Commented Jul 12, 2019 at 12:06
  • Does it show any error or something? Commented Jul 12, 2019 at 12:26
  • No error, but its redirected to checkout/cart only Commented Jul 12, 2019 at 12:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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