hydrationhub/static/pages/admin_products.js

65 lines
2.0 KiB
JavaScript

let uploadFileInput = document.getElementById('imgUpload');
let fileName = document.getElementById('fileName');
let imgUploadForm = document.getElementById('imgUploadForm');
function handleImagePresence(row) {
// Check if /api/v1/image?id=row&check returns true
// Needs to be sync
let isThere = false;
const xhr = new XMLHttpRequest();
xhr.open('GET', `/api/v1/image?id=${row.id}&check=true`, false);
xhr.send();
if (xhr.status === 200) {
try {
isThere = JSON.parse(xhr.responseText);
} catch (error) {
console.error(error);
isThere = false;
}
}
let pretty = isThere ? '<i class="bi bi-check"></i>' : '<i class="bi bi-x"></i></a>';
const template = `<a href="/api/v1/image?id=${row.id}" target="_blank">${pretty}</a> <i class="bi bi-dot"></i> <button class="btn btn-primary" onclick="uploadImage(${row.id})">Upload</button>`;
return template;
}
function uploadImage(id) {
// Open a file picker
uploadFileInput.click();
// // Open a modal to upload an image
// // Use a form
// const modal = document.getElementById('imageModal');
// modal.style.display = 'block';
imgUploadForm.action = `/api/v1/image?id=${id}`;
}
function silentFormSubmit() {
// Submit the form silently (without reloading the page or redirecting)
// Grab the form and do a POST request (dont forget to prevent default)
const xhr = new XMLHttpRequest();
xhr.open('POST', imgUploadForm.action, true);
xhr.send(new FormData(imgUploadForm));
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
console.log(xhr.responseText);
//location.reload();
createTemporaryNotification('Bild hochgeladen', 'is-success');
// Close the modal
document.getElementById('imageModal').style.display = "none";
// Empty the input
uploadFileInput.value = '';
}
};
}
uploadFileInput.addEventListener('change', function() {
fileName.innerHTML = this.files[0].name;
silentFormSubmit();
setTimeout(() => {
refreshTableByName('products');
}, 1000);
});