Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FormData append nested object

Is it possible to append nested object to FormData?

let formData = new FormData(); let data = {     title: 'title',     text: 'text',     preview: {p_title:'p title', p_text: 'p text'} };  $.each(data, function(key, value) {     formData.append(key, value); }); 

Server console - console.log(req.body)

{     title: 'title',     text: 'text',     preview: '[object Object]' } 

How can I get the exact value of preview: {p_title:'p title', p_text: 'p text'}?

like image 648
ShibinRagh Avatar asked Sep 29 '18 07:09

ShibinRagh


People also ask

How do I add nested objects to FormData?

To append an object to formData, you need to stringify it first, like this: let objToAppend= { key1: value1, key2: value2, } let formData = new FormData(); formData. append('obj', JSON. stringify(objToAppend));

Can I append object in FormData?

Yes you can, you can append to formData objects.

How do I append a form's data to FormData in Vue?

new Vue({ el: 'body', methods: { submit: function(e) { var form = document. getElementById('form'); var formData = new FormData(form); axios. post('/someUrl', formData) . then((response) => { // success callback }, (response) => { // error callback }); } } });

How does FormData append work?

The append() method of the FormData interface appends a new value onto an existing key inside a FormData object, or adds the key if it does not already exist.


2 Answers

let formData = new FormData(); let data = {   title: 'title',   text: 'text',   preview: {p_title:'p title', p_text: 'p text'} };  for(let dataKey in data) {   if(dataKey === 'preview') {     // append nested object     for (let previewKey in data[dataKey]) {       formData.append(`preview[${previewKey}]`, data[dataKey][previewKey]);     }   }   else {     formData.append(dataKey, data[dataKey]);   } } 

Console formData

for (let val of formData.entries()) {   console.log(val[0]+ ', ' + val[1]);  } 
like image 88
Sultan Aslam Avatar answered Oct 04 '22 11:10

Sultan Aslam


To append an object to formData, you need to stringify it first, like this:

let objToAppend= {   key1: value1,   key2: value2, } let formData = new FormData(); formData.append('obj', JSON.stringify(objToAppend)); 

Then on the server side to access it you need to parse it first using JSON.parse(). Hope it helps!

like image 31
Harshit Agarwal Avatar answered Oct 04 '22 10:10

Harshit Agarwal