Magento 2 Success Message – Set with Specific Location

checkoutcontrollersmagento2messagessession

I have a custom module, with a controller that apply discounts codes in payment page.

After the discount it's applied, I set a success message.
Now this message it's showing on homepage, even I apply the discount on payment page.
So to see the message I need to go on homepage.
My controller where I set the message look like this:

if($values){
        $this->chdxeckoutSession->getQuote()->setCouponCode($couponCode)
            ->collectTotals()
            ->save();
         $this->messageManager->addSuccess(
                                __(
                                    'You used coupon code "%1".',
                                    $escaper->escapeHtml($couponCode)
                                )
                            );

Does anyone know how can I set the location for this message to be in checkout/payment page?

Best Answer

Seem that you try to make an Ajax request to the custom controller in the Checkout Page. Your custom controller should return JSON format.

        $response = [
            'errors' => false,
            'message' => 'The coupon code was applied.'
        ];

    $resultJson = $this->_resultJson->create();
    return $resultJson->setData($response);

In your Js function, you need to get the response message and show it. We can follow the Coupon form on the checkout page.

Related Topic