A
A
Alexey2020-06-03 17:08:55
JavaScript
Alexey, 2020-06-03 17:08:55

How to make a request in JS similar to submit form in html?

Good afternoon,
you need to make a post request with files in JS, similar to how submitting a form in html works:

<form method="POST" enctype="multipart/form-data" action="/files/upload-multiple-files">
    <input type="file" name="files" multiple> <br/>
    <button type="submit">Submit</button>
</form>


Tried in JS in the following way but doesn't work:
var formData = new FormData();
formData.append("files", this.images);
var xhr= new XMLHttpRequest();
xhr.open("POST", "/files/upload-multiple-files");
xhr.send(formData);
xhr.onreadystatechange = function () {
      if (xhr.readyState === 4) {
           console.log(xhr)
      }
}


Tell me what the error is or in which direction to dig.

Answer the question

In order to leave comments, you need to log in

4 answer(s)
D
Dima Polos, 2020-06-03
@zeroWiNNeR

First, just pass a reference to the form to the FormData constructor, and this constructor will collect the data for you.
Secondly, how do you call your code? You need to hang processing on the submit event, pass your function there, which should accept the event object, and cancel the default action in the first line.
Thirdly, if you are uploading files, you need to add the header Content-Type: multipart/form-data
And finally: If successful, your code will output to the console not a response from the server, but an xhr object. It would be nice to check the status of the response, and then output the response to the console.

A
AUser0, 2020-06-03
@AUser0

It seems that you can write in the form id=my_form, and then document.getElementById('my_form').submit()
And if your code is needed by your code, then this.message will not work, you need to specify the element from which the data is needed more specifically. For example, again through <input type=file id=my_files name=files multiple>and

formData.append("files", document.getElementById('my_files').value);
. And the output is better through console.dir(xhr).

T
ThunderCat, 2020-06-03
@ThunderCat

firstly, the code is not clear what it is about, it looks like it was torn out of some other code with meat. There is no event on which it works (in theory, there should be a listener for submitting the form), which is hinted at by this undercode formData.append("files", this.images);, where this is, in theory, the form itself. For the rest, you need to check the console for errors locally, and accordingly xs what you have in this.images, most likely nothing, and because of this, all further pandemonium does not make sense.

I
iddqda, 2020-06-03
@iddqda

something like that:

const formData = new FormData();
const photos = document.querySelector('input[type="file"][multiple]');

formData.append('title', 'My Vegas Vacation');
for (let i = 0; i < photos.files.length; i++) {
  formData.append('photos', photos.files[i]);
}

fetch('https://example.com/posts', {
  method: 'POST',
  body: formData,
})
.then(response => response.json())
.then(result => {
  console.log('Success:', result);
})
.catch(error => {
  console.error('Error:', error);
});

seamlessly from here: https://developer.mozilla.org/en-US/docs/Web/API/F...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question