I have a set of forms relating to images (each form is used to add details to a respective image fetched from a MySQL database). The backend is handled with PHP, but the details from these images are sent to the database using the javascript Fetch API.
What I want do is show a button to 'upload more images' when the current list of forms has been submitted and the relevant data added to the database (i.e. no more images to process).
I'm using a for of
loop so I can use async/await, but I can't get it to play ball.
In the code below I've made the processImageFormats()
function async
but I can't work out how to make the if statement after item.remove()
"await" until the fetch() has happened? And is that the correct sequence of events that needs to happen?
Each time an image form is processed/submitted to the database the item.remove()
removes that form element from the document.
I tried looking at this question Using async/await with a forEach loop amongst others and thus changed it to a for of
loop from a forEach loop, but can't work out how to incorporate the await
part to solve the problem at hand.
JavaScript
var imageForms = document.querySelectorAll('.image-upload-details-form');
var uploadMoreImages = document.querySelector('#upload-images-link');
async function processImageForms() {
for (let item of imageForms) {
item.addEventListener("submit", function (evt) {
evt.preventDefault();
const formData = new FormData(this);
fetch("upload-details.php", {
method: 'post',
body: formData
}).then(function(response){
return response.text();
}).then(function(text){
console.log(text);
}).catch(function (error){
console.error(error);
})
item.remove();
// ** show or hide 'upload more images' link when there are no more forms to process - the bit that isn't working **
if (item.length === 0) {
uploadMoreImages.style.display = 'inline-block';
}
})
}
}
processImageForms();
// show or hide 'upload more images' link on pageload
if (imageForms.length === 0) {
uploadMoreImages.style.display = 'inline-block';
} else {
uploadMoreImages.style.display = 'none';
}
HTML
<a id="upload-images-link" href="upload.php">UPLOAD MORE IMAGES</a>