Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Uses of FormData over JSON

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'

like image 663
Jitin Kodian Avatar asked Sep 10 '25 22:09

Jitin Kodian


2 Answers

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!

like image 103
emanuel sanga Avatar answered Sep 12 '25 11:09

emanuel sanga


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'
}
like image 45
Arian Avatar answered Sep 12 '25 11:09

Arian