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'}
?
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));
Yes you can, you can append to formData objects.
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 }); } } });
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.
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]); }
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!
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