Call uploadPhoto()
outside of (after) the for
loop, not at the end of each loop iteration. Also, move the FormData
declaration outside of the loop.
I've also modified your original "photo_id" parameter to include the loop counter value so you will have a different photo_id parameter key for each file.
Additionally, I changed the last parameter of your call to xhr.open to "true". Your code was making synchronous xhr calls. This is usually a bad idea. I switched the last parameter to "false", making your xhr call asynchronous.
Finally, I removed the id parameter of your uploadPhoto
function, since you don't use it anyway.
I also changed the first letter of your uploading function to lowercase. You should only start a function name with an uppercase letter if it is a constructor function. This is a well accepted convention. Your code should look something like this:
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', true);
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 comes from https://stackoverflow.com/a/2117523/486979. Note that it generates a version 4 UUID.