source: Admin Scripts/Books.js@ 75f74d9

main
Last change on this file since 75f74d9 was 75f74d9, checked in by Vlado 222039 <vlado.popovski@…>, 6 weeks ago

Initial commit: Adding Book Tracker code

  • Property mode set to 100644
File size: 12.3 KB
Line 
1function editBook(bookId) {
2 const modal = document.getElementById('editModal');
3 const bookIdInput = document.getElementById('bookId');
4 if (modal) {
5 modal.style.display = 'block';
6 bookIdInput.value = bookId;
7 } else {
8 console.error("Modal element 'editModal' not found.");
9 return;
10 }
11
12 // Fetch book details and inspect the raw response
13 fetch(`../Admin Actions/GetBooks.php?id=${bookId}`)
14 .then(response => response.text()) // Change .json() to .text() to inspect raw response
15 .then(responseText => {
16 console.log("Raw response text:", responseText); // Log raw response
17
18 // Try to parse the JSON response
19 try {
20 const book = JSON.parse(responseText); // Manually parse JSON
21 console.log(book); // Log book details for debugging
22
23 // Populate the form with book data
24 const setValueIfExists = (id, value) => {
25 const element = document.getElementById(id);
26 if (element) {
27 element.value = value || ''; // Set value or empty if null/undefined
28 } else {
29 console.warn(`Element with ID '${id}' not found.`);
30 }
31 };
32
33 setValueIfExists('editTitle', book.title);
34 setValueIfExists('editIsbn', book.isbn);
35 setValueIfExists('editGenre', book.genre);
36 setValueIfExists('editPublishedYear', book.publishedyear);
37 setValueIfExists('editDescription', book.description);
38 setValueIfExists('editTotalCopies', book.totalcopies);
39 setValueIfExists('editFormat', book.format);
40 setValueIfExists('editLanguage', book.language);
41 setValueIfExists('editPublisher', book.publisher);
42 setValueIfExists('editPages', book.pages);
43
44
45 // Handle author selection (assuming multiple authors possible)
46 const authorSelect = document.getElementById('authors');
47 if (authorSelect && book.authors) {
48 book.authors.forEach(authorId => {
49 const option = authorSelect.querySelector(`option[value="${authorId}"]`);
50 if (option) option.selected = true;
51 });
52 }
53
54 // Show current cover image if exists
55 const currentImageDiv = document.getElementById('currentImage');
56 if (currentImageDiv) {
57 if (book.coverimage) {
58 currentImageDiv.innerHTML = `
59 <img src="./BookCovers/${book.coverimage}" alt="Current book cover" style="max-width: 100px; margin-top: 10px;">
60 <p>Current cover</p>
61 `;
62 } else {
63 currentImageDiv.innerHTML = '<p>No cover image uploaded</p>';
64 }
65 }
66 } catch (error) {
67 console.error('Error parsing JSON:', error);
68 }
69 })
70 .catch(error => console.error('Error fetching book details:', error));
71}
72
73
74function closeModal() {
75 document.getElementById('editModal').style.display = 'none';
76}
77
78function searchBooks() {
79 const searchInput = document.querySelector('.search-input').value.toLowerCase();
80 const tableRows = document.querySelectorAll('#booksTableBody tr');
81
82 tableRows.forEach(row => {
83 const title = row.cells[1].textContent.toLowerCase();
84 const isbn = row.cells[3].textContent.toLowerCase();
85 const author = row.cells[2].textContent.toLowerCase();
86
87 if (title.includes(searchInput) ||
88 isbn.includes(searchInput) ||
89 author.includes(searchInput)) {
90 row.style.display = '';
91 } else {
92 row.style.display = 'none';
93 }
94 });
95}
96
97function updateBook(event) {
98 event.preventDefault();
99 const formData = new FormData(event.target);
100
101 // Debug: Check what data is being sent
102 for (let pair of formData.entries()) {
103 console.log(pair[0] + ': ' + pair[1]);
104 }
105
106 fetch('../Admin Actions/UpdateBook.php', {
107 method: 'POST',
108 body: formData
109 })
110 .then(response => {
111 console.log('Response status:', response.status);
112 return response.text(); // First, get the response as text
113 })
114 .then(text => {
115 console.log('Raw response text:', text);
116 try {
117 const data = JSON.parse(text); // Try to parse it as JSON
118 console.log('Response data:', data);
119 if(data.success) {
120 closeModal();
121 location.reload();
122 } else {
123 alert(data.message || 'Failed to update book');
124 }
125 } catch (error) {
126 console.error('Failed to parse JSON:', error);
127 console.error('Raw response text:', text);
128 alert('Server returned an invalid response. Check console for details.');
129 }
130 })
131}
132
133function deleteBook(bookId) {
134 if(confirm('Are you sure you want to delete this book?')) {
135 fetch('../Admin Actions/DeleteBook.php', {
136 method: 'POST',
137 headers: {
138 'Content-Type': 'application/x-www-form-urlencoded',
139 },
140 body: `bookId=${bookId}`
141 })
142 .then(response => response.json())
143 .then(data => {
144 if(data.success) {
145 location.reload();
146 } else {
147 alert(data.message || 'Failed to delete book');
148 }
149 })
150 .catch(error => {
151 console.error('Error:', error);
152 alert('An error occurred while deleting the book');
153 });
154 }
155}
156
157function addBook(event) {
158 event.preventDefault();
159
160 const authorId = document.getElementById('authorId').value;
161 const authorSearch = document.getElementById('authorSearch').value;
162
163 console.log('Author ID:', authorId);
164 console.log('Author Search:', authorSearch);
165
166 if (!authorId || authorId.trim() === '') {
167 if (!authorSearch || authorSearch.trim() === '') {
168 alert('Please enter an author name');
169 } else {
170 alert('Please select an author from the suggestions list');
171 }
172 return;
173 }
174
175 const formData = new FormData(event.target);
176
177 // Debug log all form data
178 for (let pair of formData.entries()) {
179 console.log(pair[0] + ': ' + pair[1]);
180 }
181
182 // Continue with form submission...
183 fetch('../Admin Actions/AddBook.php', {
184 method: 'POST',
185 body: formData
186 })
187 .then(response => response.text())
188 .then(text => {
189 console.log('Server response:', text);
190 try {
191 const data = JSON.parse(text);
192 if (data.success) {
193 alert('Book added successfully!');
194 resetForm();
195 } else {
196 alert(data.message || 'Error adding book');
197 }
198 } catch (error) {
199 console.error('Invalid JSON:', text);
200 alert('Server returned invalid JSON. Check console for details.');
201 }
202 })
203 .catch(error => {
204 console.error('Fetch error:', error);
205 alert('An error occurred while adding the book');
206 });
207}
208/*
209// Add Book functionality
210function addBook(event) {
211 event.preventDefault();
212
213 console.debug('Form submission started.');
214
215 const formData = new FormData(event.target);
216
217 // Handle multiple authors for new book
218 const authorSelect = document.getElementById('addAuthors');
219 const selectedAuthors = Array.from(authorSelect.selectedOptions).map(option => option.value);
220 formData.append('authorIds', JSON.stringify(selectedAuthors));
221
222 console.debug('FormData created:', Array.from(formData.entries()));
223
224 fetch('../Admin Actions/AddBook.php', {
225 method: 'POST',
226 body: formData
227 })
228 .then(response => response.text())
229 .then(text => {
230 console.debug('Raw server response:', text);
231
232 try {
233 const data = JSON.parse(text);
234 if (data.success) {
235 alert('Book added successfully!');
236 event.target.reset();
237 // Clear current image display
238 document.getElementById('currentImage').innerHTML = '';
239 } else {
240 alert(data.message || 'Error adding book');
241 }
242 } catch (error) {
243 console.error('Invalid JSON:', text);
244 alert('Server returned invalid JSON. Check console for details.');
245 }
246 })
247 .catch(error => {
248 console.error('Fetch error:', error);
249 alert('An error occurred while adding the book');
250 });
251}
252*/
253function resetBookForm() {
254 document.getElementById('addBookForm').reset();
255 // Clear any error messages
256 document.querySelectorAll('.error-message').forEach(elem => {
257 elem.style.display = 'none';
258 });
259 // Clear current image display
260 document.getElementById('currentImage').innerHTML = '';
261}
262
263// Add these variables at the top of your Book.js file
264let currentPage = 1;
265let totalPages = 1;
266const booksPerPage = 10;
267
268function loadBooks(page, searchTerm = '') {
269 fetch(`../Admin Actions/GetBooks.php?page=${page}&search=${encodeURIComponent(searchTerm)}`)
270 .then(response => response.json())
271 .then(data => {
272 const tableBody = document.getElementById('booksTableBody');
273 tableBody.innerHTML = '';
274 console.log(data);
275
276 data.books.forEach(book => {
277 tableBody.innerHTML += `
278 <tr>
279 <td>${book.bookid}</td>
280 <td>${book.title}</td>
281 <td>${book.author_names}</td>
282 <td>${book.isbn}</td>
283 <td>${book.totalcopies}</td>
284 <td>
285 <button class="btn btn-edit" onclick="editBook(${book.bookid})">Edit</button>
286 <button class="btn btn-delete" onclick="deleteBook(${book.bookid})">Delete</button>
287 </td>
288 </tr>
289 `;
290 });
291
292 totalPages = data.totalPages;
293 currentPage = data.currentPage;
294 updatePagination();
295 })
296 .catch(error => {
297 console.error('Error loading books:', error);
298 alert('Error loading books');
299 });
300}
301
302function updatePagination() {
303 const pagination = document.querySelector('.pagination');
304 pagination.innerHTML = '';
305
306 // Previous button
307 if (currentPage > 1) {
308 pagination.innerHTML += `
309 <button onclick="changePage(${currentPage - 1})">Previous</button>
310 `;
311 }
312
313 // First page
314 pagination.innerHTML += `
315 <button ${currentPage === 1 ? 'class="active"' : ''} onclick="changePage(1)">1</button>
316 `;
317
318 // Ellipsis and middle pages
319 if (totalPages > 2) {
320 if (currentPage > 3) {
321 pagination.innerHTML += '<button>...</button>';
322 }
323
324 for (let i = Math.max(2, currentPage - 1); i <= Math.min(totalPages - 1, currentPage + 1); i++) {
325 pagination.innerHTML += `
326 <button ${currentPage === i ? 'class="active"' : ''} onclick="changePage(${i})">${i}</button>
327 `;
328 }
329
330 if (currentPage < totalPages - 2) {
331 pagination.innerHTML += '<button>...</button>';
332 }
333 }
334
335 // Last page
336 if (totalPages > 1) {
337 pagination.innerHTML += `
338 <button ${currentPage === totalPages ? 'class="active"' : ''} onclick="changePage(${totalPages})">${totalPages}</button>
339 `;
340 }
341
342 // Next button
343 if (currentPage < totalPages) {
344 pagination.innerHTML += `
345 <button onclick="changePage(${currentPage + 1})">Next</button>
346 `;
347 }
348}
349
350function changePage(page) {
351 currentPage = page;
352 const searchTerm = document.querySelector('.search-input').value;
353 loadBooks(page, searchTerm);
354}
355
356// Modify the existing searchBooks function to work with pagination
357function searchBooks() {
358 const searchTerm = document.querySelector('.search-input').value;
359 currentPage = 1; // Reset to first page on new search
360 loadBooks(1, searchTerm);
361}
Note: See TracBrowser for help on using the repository browser.