Skip to content

How to update grandtotal using knockout JS in Magento 2 checkout page

I’ve added a text field where customers can enter a coupon code. When click the “Apply Coupon” button, I am fetching the value of the coupon. I want to use this coupon value to adjust the total amount shown on the checkout page. However, I am facing difficulties making this adjustment. Is that correct?

If so, could you provide more specific details about what part I am struggling with or what exactly isn’t working as expected? This will help me provide with a more precise solution.

This is the code

 applyCoupon: function () {
            // Get the coupon code from the observable
            var couponCode = this.couponCode();
            // Check if a coupon code has been provided and if the custom module is enabled
            if (!couponCode || !this.isCustomModuleEnabled()) {
                // Show the error message using Knockout.js data binding or any other desired behavior
                 $('#errorMessagesContainer').show();
                 $('#custom_coupon_code').addClass('coupon_error');
                return;
            }
            $('#custom_coupon_code').removeClass('coupon_error');
            // Perform an AJAX request to a new controller and pass the couponCode
            var self = this;
            fullScreenLoader.startLoader();

            $.ajax({
                url: '/keeplocal/index/KeeplocalApi', // Update with the actual controller action URL
                type: 'POST',
                dataType: 'json',
                data: {
                    coupon_code: couponCode
                },
                success: function (response) {
                // console.log('response:', response);
                if (response.status) {
                    // Success handling logic
                    $('.invalid-coupon').remove(); // Remove the error message
                    // Extract and display coupon details
                    var couponDetails = response.couponDetail;
                    console.log('Coupon Barcode:', couponDetails.barcode);
                    console.log('Coupon Current Value:', couponDetails.currentValue);
                    console.log('Retailer Name:', couponDetails.isActive);
                    
                    var deferred = $.Deferred();
                    getTotalsAction([], deferred); // Trigger an update of the grand total
        
                    // if (couponDetails.isActive && couponDetails.currentValue) {
                        var totals = quote.getTotals()(); // Notice the double parentheses ()
                        console.log('totals:', totals);
                       if (totals && totals.base_grand_total) {
                        console.log('Original Grand Total:', totals.base_grand_total);
        
                        // Subtract coupon value
                        var newGrandTotal = totals.base_grand_total - couponDetails.currentValue;
                        console.log('New Grand Total:', newGrandTotal);
                        totals.base_grand_total = 34.99;
                        deferred.resolve();
                        // getTotalsAction([]);
                        // Re-fetch the updated totals to refresh the UI
                        getTotalsAction([]);
                    }
                    // }
                } else {
                    if (response.message) {
                        // Show error message from the response
                        messageList.addErrorMessage({
                          message: response.message
                        });
                        // Replace the error message within the data-ui-id attribute
                        $('[data-ui-id="checkout-cart-validationmessages-message-error"]').text(response.message);
    
                          // Create the error message structure
                        var errorMessage = $('<div>')
                                .addClass('message invalid-coupon message-error error')
                                .append($('<span>').addClass('error')
                                .append($('<div>')
                                .addClass('data-ui-id')
                                .attr('data-ui-id', 'checkout-cart-validationmessages-message-error')
                                .text(response.message)));
                       // Append the error message before the custom-coupon section
                        $('.custom-coupon').before(errorMessage);
                        // $('.custom-coupon').before('<div class="message invalid-coupon"><span class="error">' + response.message + '</span></div>');
                    } else {
                        messageList.addErrorMessage({
                          message: 'There is an issue with the coupon code.'
                        });
                    }

                    fullScreenLoader.stopLoader();
                }

                fullScreenLoader.stopLoader();
            },

                error: function () {
                    // Handle error if needed
                    self.errorMessage('An error occurred while applying the coupon.');
                    fullScreenLoader.stopLoader();
                }
            });
        },

Please tell me where I am doing mistake to update the grand total of the checkout page.