New formdata in javascript
In JavaScript, the FormData
object is used to construct a new form that can be sent to a server. It allows you to easily add and manipulate form data, such as text fields, file inputs, and checkboxes.
Here's an example of how to create a new FormData
object:
const formData = new FormData();
You can then add form data to the object using the append()
method:
formData.append('name', 'John Doe');
formData.append('age', 30);
formData.append('file', fileInput.files[0]);
In this example, we're adding three form data items: name
, age
, and a file input.
You can also add multiple values for the same key using the append()
method:
formData.append('interests', ['reading', 'hiking', 'coding']);
This will add an array of values for the interests
key.
Once you've added all the form data, you can send it to a server using the XMLHttpRequest
object or the fetch()
API:
const xhr = new XMLHttpRequest();
xhr.open('POST', 'https://example.com/api/form', true);
xhr.send(formData);
Or:
fetch('https://example.com/api/form', {
method: 'POST',
body: formData,
})
Note that when sending a FormData
object, the browser will automatically set the Content-Type
header to multipart/form-data
, which is the standard format for sending form data.
Here's a complete example:
const formData = new FormData();
formData.append('name', 'John Doe');
formData.append('age', 30);
formData.append('file', fileInput.files[0]);
const xhr = new XMLHttpRequest();
xhr.open('POST', 'https://example.com/api/form', true);
xhr.send(formData);
This code creates a new FormData
object, adds three form data items, and sends it to a server using the XMLHttpRequest
object.
Alternatively, you can use the fetch()
API to send the form data:
const formData = new FormData();
formData.append('name', 'John Doe');
formData.append('age', 30);
formData.append('file', fileInput.files[0]);
fetch('https://example.com/api/form', {
method: 'POST',
body: formData,
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error(error));
This code creates a new FormData
object, adds three form data items, and sends it to a server using the fetch()
API. The response is then parsed as JSON and logged to the console.