Quantcast
Channel: Webkul Blog
Viewing all articles
Browse latest Browse all 5556

Redirect to a page after ajax request Magento2

$
0
0

Magneto-Code-Snippet

If you send an ajax request and want to redirect your controller to a particular controller , or if you want to redirect back to previous page, then you can follow 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 customer/account page.

Thank you.


Viewing all articles
Browse latest Browse all 5556

Latest Images

Trending Articles



Latest Images