I am developing an e-commerce web app using spring boot, mysql and thymeleaf. I was able to add product to cart using HttpSession but the problem is that I have to click on refresh button before am able to view the added product on the cart. I am using HttpSession because I want the guest users should be able to add to cart without login. I would like to view the product added to cart once the button is click without refreshing the page. Please i need someone to help me out.
@GetMapping("/customers/add/cart")
@ResponseBody
public ModelAndView addProductToCart(String productId, int quantity, HttpSession session) {
ModelAndView modelAndView = new ModelAndView();
try {
Product product = productService.getProduct(productId);
if (session.getAttribute("cart") == null) {
List<CartItem> cartItems = new ArrayList<>();
cartItems.add(new CartItem(product, quantity));
session.setAttribute("cart", cartItems);
} else {
List<CartItem> cartItems = (List<CartItem>) session.getAttribute("cart");
int index = this.exists(productId, cartItems);
if (index == -1) {
cartItems.add(new CartItem(product, quantity));
} else {
int qty = cartItems.get(index).getQuantity() + 1;
cartItems.get(index).setQuantity(qty);
}
session.setAttribute("cart", cartItems);
}
modelAndView.setViewName("redirect:/products/detail/" + productId);
//modelAndView.setViewName("redirect:/index");
return modelAndView;
} catch (ProductNotFoundException e) {
modelAndView.setViewName("error/404");
return modelAndView;
}
}
private int exists(String id, List<CartItem> cartItems) {
for (int i = 0; i < cartItems.size(); i++) {
if (cartItems.get(i).getProduct().getProductId().equalsIgnoreCase(id)) {
return i;
}
}
return -1;
}
AJAX function
function addToCart() {
$.ajax({
url: "/customers/add/cart",
type: 'get',
data: {
quantity: function () {
return $("#productQty").val();
},
productId: function () {
return $("#productId").val();
},
_csrf: function () {
return $("input[name='_csrf']").val();
}
},
error: function (jqXhr, status, errorMessage) {
$("#message").after('<div class="alert alert-danger text-center">Error</div>')
},
success: function (data) {
//alert(data);
// $("#headerCartWrap").load(" #headerCartWrap")
$("#message").after('<div class="alert alert-success text-center">Product added to cart successfully</div>')
}
});
}
I was able to add product to cart using HttpSession but the problem is that I have to click on refresh button before am able to view the added product on the cart.