<!DOCTYPE html>
<html>
<head>
<title>Shopping Cart</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="script.js"></script>
</head>
<body>
<h1>Shopping Cart</h1>
<div id="cart"></div>
</body>
</html>
$(document).ready(function() {
// Dummy JSON data representing products
var products = [
{ id: 1, name: "Product 1", price: 10 },
{ id: 2, name: "Product 2", price: 20 },
{ id: 3, name: "Product 3", price: 30 }
];
// Function to render the cart
function renderCart(cartItems) {
var cart = $("#cart");
cart.empty();
if (cartItems.length === 0) {
cart.append("<p>Cart is empty.</p>");
} else {
var total = 0;
var cartTable = $("<table>");
var tableHeader = $("<tr><th>Product</th><th>Price</th></tr>");
cartTable.append(tableHeader);
$.each(cartItems, function(index, cartItem) {
var product = products.find(function(p) {
return p.id === cartItem.productId;
});
var tableRow = $("<tr><td>" + product.name + "</td><td>" + product.price + "</td></tr>");
cartTable.append(tableRow);
total += product.price;
});
var totalRow = $("<tr><td><strong>Total:</strong></td><td>" + total + "</td></tr>");
cartTable.append(totalRow);
cart.append(cartTable);
}
}
// Ajax request to get cart data
$.ajax({
url: "dummy_cart_data.json",
method: "GET",
success: function(response) {
renderCart(response.cartItems);
},
error: function() {
console.log("Error: Failed to retrieve cart data.");
}
});
});
{
"cartItems": [
{ "productId": 1 },
{ "productId": 3 }
]
}