0

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.

0

1 Answer 1

1

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
        }
    });
});
4
  • My problem is that I am showing some error/warning messages and want to display them in the cart rather than the page they are on, would this do the trick of carrying the error messages through to cartt?
    – Greg
    Jan 21, 2019 at 17:12
  • If you add your messages to checkout/session in the controller they should appear in checkout/cart after the redirect Jan 21, 2019 at 17:16
  • hymmm... That would solve all my problems! Any ideas or suggestion how can I achieve that? Link etc? :D
    – Greg
    Jan 21, 2019 at 17:23
  • If your controller extends \Magento\Framework\App\Action\Action, as I suppose it does, your can add any session message using $this->messageManager, for instance magento.stackexchange.com/a/127689/3566 Jan 21, 2019 at 17:31

Your Answer

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

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