I have been working on this app which simulates a shopping cart to learn Spring framework. When I the user clicks "Add Item" I want to stay on the same site, create a product object and add it to the cart object in the background(Optionally display a message on the site?). And when the user is done adding and clicks "Generate Receipt" I want to display another page with all their carts content and total price. The second part about redirecting to a new page and displaying all their cart is fine but I could not figure out how to stay on the same page when clicked on "Add Item" and displaying an "Item Added" kind of message on the site. How could I do this.
Site looks like this :
Here is my Spring Application File :
package spring.shoppingcart;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.sql.Array;
import java.util.ArrayList;
import java.util.List;
@SpringBootApplication
@RestController
public class SpringShoppingApplication {
private static ProductDb productDb = new ProductDb();
public static void main(String[] args) {
SpringApplication.run(SpringShoppingApplication.class, args);
}
@PostMapping("/generateReceipt")
public static String generateReceipt() {
return "Your Receipt : ";
}
@PostMapping("/addToCart")
public static String addToCart(
@RequestParam(value = "productName", defaultValue = "") String productName,
@RequestParam(value = "productQuantity", defaultValue = "") String productQuantity
) {
if (productDb.getProduct(productName) == null) {
return "No Such Product : " productName;
} else if (!isInteger(productQuantity)) {
return "Quantity Should Be An Integer : " productQuantity;
}else{
return "Product Name : " productDb.getProduct(productName).name() " Product Quantity : " productQuantity;
}
}
public static boolean isInteger(String str) {
try {
Integer.parseInt(str);
return true;
} catch (NumberFormatException e) {
return false;
}
}
}
And here is my HTML file :
<!DOCTYPE HTML>
<html>
<head>
<title>Shopping Cart</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" xmlns:th="http://www.thymeleaf.org"/>
</head>
<body>
<style>
html {
color: whitesmoke;
background-color: steelblue;
}
#content {
text-align: center;
vertical-align: center;
}
#db {
text-align: center;
background-color: cornflowerblue;
}
#tab {
margin-left: auto;
margin-right: auto;
}
</style>
<div id="content">
<form method="post">
Product Name :<br><br>
<input type="text" name="productName">
<br><br>
Product Quantity :<br><br>
<input type="text" name="productQuantity">
<br><br>
<button type="submit" formaction="/addToCart">Add to Cart</button>
<button type="submit" formaction="/generateReceipt">Generate Receipt</button>
</form>
</div>
<br><br>
</body>
</html>
CodePudding user response:
You can use some jQuery Ajax to do POST requests for this purpose. You would have something like this in a someScriptName.js file:
$(document).ready(function () {
$("#my-form").submit(function (event) {
var productData = {}
productData["productName"] = $("#productNameId").val();
productData["productQuantity"] = $("#productQuantityId").val();
$("#success-msg").hide();
$("#error-msg").hide();
$.ajax({
type: "POST",
contentType: "application/json",
url: "/addToCart",
data: JSON.stringify(productData),
dataType: 'json',
cache: false,
timeout: 60000,
success: function (data) {
$("#success-msg").show();
},
error: function (e) {
$("#error-msg").show();
}
});
});
});
You would have to include this .js as part of your HTML:
<script type="text/javascript" src="js/someScriptName.js"></script>
CodePudding user response:
There are to many ways to solve this problem but in this way you can add item.
- You are using html form this will reload page when you click on submit
<form method="post">
Product Name :<br><br>
<input type="text" name="productName">
<br><br>
Product Quantity :<br><br>
<input type="text" name="productQuantity">
<br><br>
<button type="submit" formaction="/addToCart">Add to Cart</button>
<button type="submit" formaction="/generateReceipt">Generate Receipt</button>
</form>
- So the simple solution is use javascript for send request
let url = "https://reqbin.com/echo/post/json";
let xhr = new XMLHttpRequest();
xhr.open("POST", url);
xhr.setRequestHeader("Accept", "application/json");
xhr.setRequestHeader("Content-Type", "application/json");
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
console.log(xhr.responseText);
}};
let data = `{
"Id": 78912,
"Customer": "Jason Sweet",
"Quantity": 1,
"Price": 18.00
}`;
xhr.send(data);
# Your full page will be like this
<html>
<body>
<form id="my-form">
Product Name :<br><br>
<input type="text" name="productName">
<br><br>
Product Quantity :<br><br>
<input type="text" name="productQuantity">
<br><br>
<button type="submit">Add to Cart</button>
<button type="submit">Generate Receipt</button>
</form>
<script>
document.querySelector(document).ready(function () {
document.querySelector("#my-form").submit(function (event) {
var productData = {}
productData["productName"] = document.querySelector("#productNameId").value;
productData["productQuantity"] = document.querySelector("#productQuantityId").value;
$.ajax({
type: "POST",
contentType: "application/json",
url: "/addToCart",
data: JSON.stringify(productData),
dataType: 'json',
cache: false,
timeout: 60000,
success: function (data) {
// Show some success message
},
error: function (e) {
// Show some error message
}
});
});
});
</script>
</body>
</html
- You need to add some changes in code bassed your requirments