Athenaeum/static/js/book.js

95 lines
3.4 KiB
JavaScript
Raw Normal View History

2025-05-24 16:47:32 +02:00
document.addEventListener('DOMContentLoaded', async () => {
const urlParams = new URLSearchParams(window.location.search);
const bookId = urlParams.get('id');
2025-05-24 19:23:52 +02:00
const bookDetails = document.getElementById('book-details');
if (!bookId) {
bookDetails.innerHTML = `
<div class="col-12 text-center py-5">
<h2 class="text-danger">Nieprawidłowe ID książki</h2>
<a href="/" class="btn btn-gothic mt-3">Powrót do strony głównej</a>
</div>
`;
return;
}
2025-05-24 16:47:32 +02:00
try {
const response = await fetch(`/api/ksiazki/${bookId}`);
2025-05-24 19:23:52 +02:00
if (!response.ok) {
throw new Error(`Status: ${response.status}`);
}
2025-05-24 16:47:32 +02:00
const book = await response.json();
2025-05-25 16:25:22 +02:00
2025-05-24 16:47:32 +02:00
document.getElementById('book-title').textContent = book.tytul;
document.getElementById('book-author').textContent = `Autor: ${book.autor}`;
document.getElementById('book-price').textContent = `Cena: ${book.cena} PLN`;
2025-05-24 19:23:52 +02:00
document.getElementById('book-description').textContent = book.opis;
document.getElementById('book-cover').src = book.obraz_url;
2025-05-25 16:25:22 +02:00
// Dodaj obsługę przycisku "Dodaj do koszyka"
document.querySelector('.btn-gothic').addEventListener('click', async () => {
const token = localStorage.getItem('token');
if (!token) {
alert('Musisz być zalogowany, aby dodać książkę do koszyka');
window.location.href = '/login.html';
return;
}
try {
const response = await fetch('/api/add-to-cart', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${token}`
},
body: JSON.stringify({
book_id: parseInt(bookId),
quantity: 1
})
});
if (response.ok) {
alert('Dodano do koszyka!');
} else {
const error = await response.json();
alert(error.error || 'Wystąpił błąd');
}
} catch (error) {
console.error('Błąd:', error);
alert('Wystąpił błąd podczas dodawania do koszyka');
}
});
2025-05-24 16:47:32 +02:00
} catch (error) {
console.error('Błąd:', error);
2025-05-24 19:23:52 +02:00
bookDetails.innerHTML = `
<div class="col-12 text-center py-5">
<h2 class="text-danger">Błąd ładowania książki</h2>
<p>${error.message}</p>
2025-05-24 16:47:32 +02:00
<a href="/" class="btn btn-gothic mt-3">Powrót do strony głównej</a>
</div>
`;
}
});
2025-05-25 16:25:22 +02:00
document.querySelector('button').addEventListener('click', async () => {
try {
const response = await fetch(`/api/add-to-cart`, {
method: 'POST',
headers: getAuthHeaders(),
body: JSON.stringify({
book_id: new URLSearchParams(window.location.search).get('id'),
quantity: 1
})
});
if (response.status === 401) {
window.location.href = '/login.html';
return;
}
// ... reszta obsługi
} catch (error) {
console.error('Error:', error);
}
});