1

I am trying to delete an item from shopping cart using Ajax with javascript, but I have trouble passing parameters to the controller. The parameters are null in controller.

My javascript code shows as below:

function removeRow(itemId, rowID){
        if (xmlHttp == null)
        {
            alert("Your browser does not support AJAX!");
            return;
        }
        var query = "action=remove&item=" + itemId;

        /* alert(query); */
        xmlHttp.onreadystatechange = function stateChanged()
        {
            if (xmlHttp.readyState == 4)
            {
                var row = document.getElementById(rowID);
                row.parentNode.removeChild(row);
            }
        };
        xmlHttp.open("GET", "addTo.htm", true);
        xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        xmlHttp.send(query);
        return false; 
        /* var row = document.getElementById(rowID);
        row.parentNode.removeChild(row); */

}

My controller code shows as below:

@Controller

@RequestMapping("/addTo.htm")
public class AddToController{
    @RequestMapping(method=RequestMethod.GET)
    protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception {
        HttpSession session = request.getSession();
        String action = request.getParameter("action");
        System.out.println(action);
        ModelAndView mv = new ModelAndView();
        ArrayList<Item> cart;
        if(action.equals("remove")){
            System.out.println("cart size is" + cart.size());
            Long itemId = Long.parseLong(request.getParameter("item"));
            ItemDAO itemDao= new ItemDAO();
            Item item = itemDao.get(itemId);
            cart.remove(item);
            System.out.println(cart.size());
        }
        return mv;
    }
}

The action and item are null in the controller.

Can anyone help with this problem?

1 Answer 1

1

You're sending a GET request, so add the parameters as a query after your URL:

xmlHttp.open("GET", "addTo.htm?" + query, true);

and pass in null (rather than your query string) when calling the .send method:

xmlHttp.send(null);

Also, the "application/x-www-form-urlencoded" header is only used when you're sending serialised parameters but using POST, so remove the xmlHttp.setRequestHeader line.

More info: https://developer.mozilla.org/en-US/docs/AJAX/Getting_Started

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.