0

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>
Pallab
  • 53
  • 1
  • 6
  • 2
    Hard to diagnose without knowing the error message. – Roamer-1888 Feb 19 '22 at 16:46
  • no error it's showing it's taking me to the error function of my ajax – Pallab Feb 19 '22 at 16:52
  • 1
    If the error callback runs, then there must have been an error. The `error` callback receives three arguments; `(jqXHR jqXHR, String textStatus, String errorThrown)`. The error message is represented by `textStatus` and/or `errorThrown`. Log them both to discover the error message. – Roamer-1888 Feb 19 '22 at 17:08
  • Show your action class fully. Probably you have a problem with json result serialization. The plugin might supress errors during the process but you need to control the json structure returned to the client. In the previous answer I suggested to use `root` parameter for the result to the action, because you needed a property to return. Now you have some properties that might break the serialization process and should be excluded. [This](https://stackoverflow.com/a/24445373/573032) is a similar problem. – Roman C Feb 21 '22 at 08:42
  • @RomanC i have added the whole action class, Please check I have also tried by creating a new action class with a single method where i created variable and tried to return that but still that was taking me to the error thing, I don't understand why it is not working – Pallab Feb 22 '22 at 13:50
  • The error message is still unknown. The action class should extend `ActionSupport` to get errors. – Roman C Feb 22 '22 at 14:19
  • @RomanC how will i get to know what is the error actually – Pallab Feb 22 '22 at 14:25
  • Errors are written to the server log, you can also call `hasErrors()`. – Roman C Feb 22 '22 at 14:28
  • @RomanC this is what i see in the serverlog -- SEVERE [http-nio-9494-exec-39] org.apache.catalina.core.StandardWrapperValve.invoke Servlet.service() for servlet [default] in context with path [/OnlineTableBooking] threw exception [Filter execution threw an exception] with root cause java.lang.NoClassDefFoundError: org/apache/commons/lang3/StringUtils – Pallab Feb 22 '22 at 14:29
  • @RomanC i have just included commons-lang3-3.1.jar and now it's working, Thank you so much for your help. – Pallab Feb 22 '22 at 14:33
  • I thought the problem in serialization to json. You can change the value of the param to `noData` to return only this property or put this property to another object which you can use for Json and configure it to the result. – Roman C Feb 22 '22 at 14:47

0 Answers0