Convert JS Object to form data
If you have an object, you can easily create a FormData object and append the names and values from that object to formData.
You haven't posted any code, so it's a general example;
var form_data = new FormData();
for ( var key in item ) {
form_data.append(key, item[key]);
}
$.ajax({
url : 'http://example.com/upload.php',
data : form_data,
processData : false,
contentType : false,
type: 'POST'
}).done(function(data){
// do stuff
});
There are more examples in the documentation on MDN
With ES6 and a more functional programming approach @adeneo's answer could looks like this:
function getFormData(object) {
const formData = new FormData();
Object.keys(object).forEach(key => formData.append(key, object[key]));
return formData;
}
And alternatively using .reduce()
and arrow-functions:
const getFormData = object => Object.keys(object).reduce((formData, key) => {
formData.append(key, object[key]);
return formData;
}, new FormData());
This function adds all data from object to FormData
ES6 version from @developer033:
function buildFormData(formData, data, parentKey) {
if (data && typeof data === 'object' && !(data instanceof Date) && !(data instanceof File)) {
Object.keys(data).forEach(key => {
buildFormData(formData, data[key], parentKey ? `${parentKey}[${key}]` : key);
});
} else {
const value = data == null ? '' : data;
formData.append(parentKey, value);
}
}
function jsonToFormData(data) {
const formData = new FormData();
buildFormData(formData, data);
return formData;
}
const my_data = {
num: 1,
falseBool: false,
trueBool: true,
empty: '',
und: undefined,
nullable: null,
date: new Date(),
name: 'str',
another_object: {
name: 'my_name',
value: 'whatever'
},
array: [
{
key1: {
name: 'key1'
}
}
]
};
jsonToFormData(my_data)
jQuery version:
function appendFormdata(FormData, data, name){
name = name || '';
if (typeof data === 'object'){
$.each(data, function(index, value){
if (name == ''){
appendFormdata(FormData, value, index);
} else {
appendFormdata(FormData, value, name + '['+index+']');
}
})
} else {
FormData.append(name, data);
}
}
var formData = new FormData(),
your_object = {
name: 'test object',
another_object: {
name: 'and other objects',
value: 'whatever'
}
};
appendFormdata(formData, your_object);
Try JSON.stringify function as below
var postData = JSON.stringify(item);
var formData = new FormData();
formData.append("postData",postData );