Magento2 jQuery Redirect – Controller Redirect on jQuery Post Request from PHTML Template

jquerymagento2magento2.2redirect

I want to redirect user on button click from .phtml template file, however, really struggle to find a working solution.

Here is my controller with path of /batchorder/index/addtocart:

public function execute()
    {
        $this->_redirect('checkout/cart/index');
    }

Here is my template file with the post request:

$("#addToCart").click(function(){ 
     let controllerUrl = "<?php echo $block->getUrl('batchorder/index/addtocart'); ?>"
     $.post( controllerUrl ); 
 }

When I navigate to www.mydomain.com/batchorder/index/addtocart in my browser, the redirect is working fine, however, when hitting the button with id #addToCart the redirect is not working.

Is this even possible with the jQuery post request? Is there alternative way? I am sending some information to the controller with the post request and want to redirect in the controller once the operations are finished.

Any guidance will be highly appreciated.

Best Answer

What I would do is returning the url to redirect in a JSON object (for example) as response to Ajax call, and then deal with that response in the .phtml

So...

public function execute()
{
    $response = new stdClass();
    $response->url = false;
    // your logic here, where you set the redirect url in $response->url if proceed
    die(json_encode($response));
}

And then, in .phtml

$("#addToCart").click(function(){ 
    var controllerUrl = "<?php echo $block->getUrl('batchorder/index/addtocart'); ?>";
    $.post( controllerUrl, function( response ) {
        if (response.url){
            window.location.href = response.url;
        } else {
            // show some error
        }
    });
});
Related Topic