A
A
Anatoly2021-06-11 01:59:46
JavaScript
Anatoly, 2021-06-11 01:59:46

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>


I cut out the code for sending via ajax from the code, since it works great and is not relevant to the question.

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question