I use JSON
to send data to the server side. If I had to send files, I converted the file to base64
and I send it through JSON
. Recently I came across FormData
. MDN says
The FormData object lets you compile a set of key/value pairs to send using XMLHttpRequest. It is primarily intended for use in sending form data, but can be used independently from forms in order to transmit keyed data.
(The above definition reminded me about JSON
itself)
FormData
can be used to send files directly without converting to base64
.
So my question is 'Is there any other advantage to using Formdata
over JSON
'
The main benefit of json over formdata is fields nesting!
With json, you can nest fields as you want(dunno if there is a limit), but with formdata, you have to manually stringify the fields first and then add them as a string to the key that would own that nested object.
Programmatically
var myObject = {1: 1, 2: {3: 4}}
with formdata, you would have to stringify the object {3: 4}
first before adding it to the formdata, else, it would passed as ['object Object']
My advice:
if (action is 'sending files') {
// use formdata
} else {
// use json
}
pro hint: don't send files as base64, it has more disadvantages than advantages!
If you send fields having null values, being content-type as formdata, the fields will be removed by default. Example:
{
name: 'Foo',
age: null
}
What will be sent by formdata will be:
{
name: 'Foo'
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With