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()

Here is my template file with the post request:

     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.


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


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

And then, in .phtml

    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
  • 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 at 17:12
  • If you add your messages to checkout/session in the controller they should appear in checkout/cart after the redirect – Raul Sanchez Jan 21 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 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 – Raul Sanchez Jan 21 at 17:31

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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