Ajax call always going to error function in Struts 2

170 Views Asked by At

I am trying to return json from action by ajax call in struts 2 but it's always taking me to the error function. Here i am trying to take the cartsize by ajax call and want to print the cartsize whenever someone click on add to cart but it's taking me to error function always

Here is my ajax call

<script type="text/javascript">

            function addProductToCart(productId)
            {
                
                $.ajax({
                    url: 'addProductToCart',
                    method: "POST",
                    data: {productId: productId},
                    success: function (data) {
                        alert("In success");
                         $('#result').html(data.cartSize);
                         alert(data.cartSize);

                        
                    },
                    error: function (jqXHR, exception) {
                        console.log('Error occured!!');
                        alert("Error");
                    }
                });

                }
                </script>

My Action Class only the addProduct method

public String addProductToCart(){
        System.out.println("Cart: " + productId);
        MenuServices item = new MenuServices();
        if (sessionMap.get("Cart") == null) {
            HashMap<Integer, Menu> cart = new HashMap<>();

            try {
                Menu product = item.fetchProduct(productId);
                cart.put(productId, product);
                getSessionMap().put("Cart", cart);
            } catch (Exception ex) {
                Logger.getLogger(ReservationAction.class.getName()).log(Level.SEVERE, null, ex);
            }

        } else {
            HashMap cart = (HashMap) sessionMap.get("Cart");
            try {
                Menu product = item.fetchProduct(productId);
                cart.put(productId, product);
                getSessionMap().put("Cart", cart);
            } catch (Exception ex) {
                Logger.getLogger(ReservationAction.class.getName()).log(Level.SEVERE, null, ex);
            }
        }

        HashMap cart = (HashMap) sessionMap.get("Cart");
        setCartSize(cart.size());
        return ActionSupport.SUCCESS;
    }

Struts.xml

<package name="base" namespace="/" extends="json-default">
    <action name="addProductToCart" class="com.tablebooking.actions.ReservationAction" method = "addProductToCart">
    <result type="json">
        <param name="root">action</param>
    </result>
</action>
    </package>
0

There are 0 best solutions below