Ensure to call the uploadPhoto()
function outside of the for
loop rather than at the end of each iteration. Additionally, move the declaration of FormData
outside of the loop.
I have also adjusted the "photo_id" parameter to include the loop counter value, providing a unique key for each file.
Moreover, I updated the last parameter of the xhr.open call to be set as "false" instead of "true" to make the xhr request asynchronous, which is generally preferred over synchronous calls.
Furthermore, I removed the id parameter from the uploadPhoto
function since it was not being utilized.
It is also recommended to start function names with a lowercase letter unless they are constructor functions. Therefore, your code snippet should reflect this convention:
if(files.length <= 6) {
var formData = new FormData();
for(var i = 0; i < files.length; i++) {
var id = getUuid();
formData.append('action', 'uploadPhoto');
formData.append('photo_' + i + "_id", id);
formData.append('file'+id, files[i]);
}
uploadFile(formData);
}
function uploadFile(formData) {
var xhr = new XMLHttpRequest();
xhr.open('POST', 'uploadPhoto.php', false);
xhr.send(formData);
}
function getUuid() {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8);
return v.toString(16);
});
}
The getUuid function implementation can be found at , generating a version 4 UUID.