Answer the question
In order to leave comments, you need to log in
Does it make sense to use the form tag if I don't understand how to do without FormData()?
Task: Filling out a form with a questionnaire (Name, Surname) and a few photos (via multiple).
When uploading one photo, there are no problems with sending it to the server, if I specify several photos, then only one is sent. I solved the issue using the code below, but the question arose, if I am forced to use FormData(), is there any point in using the tag <form>
? Or was the task solved somehow differently, and form already has some kind of object with data?
<form action="" method="post" enctype="multipart/form-data" id="myform">
<input type="file" name="images" multiple id="myimage">
<input type="text" name="name" placeholder="Имя" id="name">
<input type="text" name="lastname" placeholder="Фамилия" id="lastname">
<input type="submit">
</form>
<script>
const images = document.getElementById('myimage');
const name = document.getElementById('name');
const lastname = document.getElementById('lastname');
const my_submit = function(e) {
e.preventDefault();
let form = new FormData();
form.append('name', name.value);
form.append('lastname', lastname.value);
let a = 0;
for (let file of images.files) {
a++;
form.append('file['+ a +']', file);
}
// for (let i in images.files) { form.append('file['+ i +']', images.files[i]); }
};
const form = document.getElementById('myform');
form.addEventListener("submit", my_submit, true);
</script>
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question