If you send an Ajax request and want to redirect your controller to a particular controller, or if you want to redirect back to the previous page, then you can follow the following code:
<?php namespace Webkul\Test\Controller\Index; use \Magento\Framework\App\Action\Action; class CustomAjax extends Action { public function execute() { $url = $this->_url->getUrl('customer/account');//You can give any url, or current page url //Your ajax Request Code return $this->goBack($url); } protected function goBack($backUrl = null) { //if controller request is not ajax type if (!$this->getRequest()->isAjax()) { if ($backUrl || $backUrl = $redirectUrl) { $resultRedirect = $this->resultRedirectFactory->create(); $resultRedirect->setUrl($backUrl); return $resultRedirect; } } //if request is ajax type then it create result of json type and return the result $result = []; if ($backUrl || $backUrl = $redirectUrl) { $result['backUrl'] = $backUrl; } $this->getResponse()->representJson( $this->_objectManager->get('Magento\Framework\Json\Helper\Data') ->jsonEncode($result) ); } }
After your Ajax request code, it redirects you to the customer/account page.
I hope this blog will help you with Redirect to a Page after Ajax Request Magento 2. You may also check our wide range of best Magento 2 Extensions.
Please reach out to our team via a support ticket if you have any queries.
Try this and if you have any queries then just comment below 🙂
1 comments