Gitlab@Informatics

Skip to content
Snippets Groups Projects
Commit 9b9f1fee authored by 65160381's avatar 65160381
Browse files

8.4

parent d0f51468
No related branches found
No related tags found
No related merge requests found
Pipeline #605 passed with warnings
......@@ -169,6 +169,76 @@ app.post('/login', async (req, res) => {
}
});
// เพิ่มสินค้าใหม่
app.get('/api/user/products', async (req, res) => {
if (!req.session.user) {
return res.status(401).send('User not logged in');
}
const userId = req.session.user.id; // ใช้ user_id จาก session
try {
const connection = await pool.getConnection();
const [products] = await connection.query(
'SELECT * FROM products WHERE user_id = ?',
[userId]
);
connection.release();
res.json(products);
} catch (err) {
console.error('Error fetching user products:', err);
res.status(500).send('Error fetching user products');
}
});
// เพิ่มสินค้าใหม่
app.post('/api/products', (req, res) => {
if (!req.session.user) {
return res.status(401).send('User not logged in');
}
const { productName, productPrice, productImg } = req.body;
const userId = req.session.user.id; // user_id จาก session
pool.query(`
INSERT INTO products (product_name, product_price, product_img, user_id)
VALUES (?, ?, ?, ?)
`, [productName, productPrice, productImg, userId], (err, results) => {
if (err) {
return res.status(500).send('Error adding product');
}
res.send('Product added successfully');
});
});
// ดึงสินค้าของผู้ใช้
app.get('/api/user/products', (req, res) => {
if (!req.session.user) {
return res.status(401).send('User not logged in');
}
const userId = req.session.user.id;
pool.query(`
SELECT * FROM products WHERE user_id = ?
`, [userId], (err, results) => {
if (err) {
return res.status(500).send('Error fetching user products');
}
res.json(results);
});
});
// ดึงสินค้าทั้งหมด
app.get('/api/products', (req, res) => {
pool.query('SELECT * FROM products', (err, results) => {
if (err) {
return res.status(500).send('Error fetching products');
}
res.json(results);
});
});
app.use(express.json()); // สำหรับการ parse ข้อมูลแบบ JSON
app.use(express.urlencoded({ extended: true })); // สำหรับการ parse ข้อมูลแบบ URL-encoded
......
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Cart ASA</title>
<link rel="stylesheet" href="styles/cart.css">
</head>
<body>
<header>
<h1>ASA Cart</h1>
</header>
<div class="cart-items" id="cart-items">
<!-- Cart items will be dynamically loaded here -->
</div>
<footer>
<p>&copy; 2025 ASA</p>
<div class="checkout" onclick="goToCheckout()">Checkout</div>
</footer>
<script>
// Load cart items from the API
async function loadCart() {
try {
const response = await fetch('/api/cart');
const cart = await response.json();
const cartItemsContainer = document.getElementById('cart-items');
cartItemsContainer.innerHTML = '';
if (cart.length === 0) {
cartItemsContainer.innerHTML = '<p>Your cart is empty!</p>';
}
cart.forEach(item => {
const itemDiv = document.createElement('div');
itemDiv.classList.add('cart-item');
itemDiv.innerHTML = `
<img src="${item.product_img}" alt="${item.product_name}">
<div>
<h3>${item.product_name}</h3>
<p>Price: $${item.product_price}</p>
<p>Total Price: $<span id="total-price-${item.product_id}">${item.total_price}</span></p>
</div>
<div>
<input type="number" value="${item.quantity}" min="1" onchange="updateQuantity(${item.product_id}, this.value)">
<button onclick="removeFromCart(${item.product_id})">Remove</button>
</div>
`;
cartItemsContainer.appendChild(itemDiv);
});
} catch (error) {
console.error('Error loading cart items:', error);
}
}
async function updateQuantity(productId, newQuantity) {
await fetch(`/api/cart/${productId}`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ quantity: newQuantity })
});
loadCart(); // Reload the cart after updating
}
async function removeFromCart(productId) {
await fetch(`/api/cart/${productId}`, { method: 'DELETE' });
loadCart(); // Reload the cart after removal
}
function goToCheckout() {
window.location.href = 'checkout.html';
}
// Load cart items when page loads
loadCart();
</script>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Your Products</title>
<link rel="stylesheet" href="styles/home.css">
</head>
<body>
<header>
<h1>Your Products</h1>
</header>
<div class="products" id="user-products">
<!-- User's products will be dynamically loaded here -->
</div>
<footer>
<p>&copy; 2025 ASA</p>
</footer>
<script>
// Function to load products posted by the logged-in user
async function loadUserProducts() {
try {
const response = await fetch('/api/user/products');
const products = await response.json();
const productContainer = document.getElementById('user-products');
productContainer.innerHTML = ''; // Clear the container
if (products.length === 0) {
productContainer.innerHTML = '<p>You have no products listed.</p>';
}
products.forEach(product => {
const productDiv = document.createElement('div');
productDiv.classList.add('product');
productDiv.innerHTML = `
<img src="${product.product_img}" alt="${product.product_name}">
<h3>${product.product_name}</h3>
<p>Price: $${product.product_price}</p>
`;
productContainer.appendChild(productDiv);
});
} catch (error) {
console.error('Error loading user products:', error);
}
}
// Call function to load user products when page loads
loadUserProducts();
</script>
</body>
</html>
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment