There are many ways to send data from html form to backend through POST
request. Out of them, the primary way is FormData
. This is ideal when you have simple input fields. But it could become very complex when you need to send array of data. The below code can convert the nested javascript object into formdata –
const formData = new FormData(); buildFormData(formData, objToSendAsPostRequest); buildFormData = (formData, data, parentKey) => { if (data && typeof data === 'object' && !(data instanceof Date) && !(data instanceof File)) { Object.keys(data).forEach(key => { this.buildFormData(formData, data[key], parentKey ? `${parentKey}[${key}]` : key); }); } else { const value = data == null ? '' : data; formData.append(parentKey, value); } }
You may also like –
Example
Suppose you have an object –
var obj = { name : { first: 'Akash', middle: 'Rishi', last: 'Mittal', }, }
Now if you want to send this complete javascript object obj
as your POST request using FormData, then we can simply call our defined function buildFormData
–
var formdata = new FormData(); buildFormData(formdata, obj);
At the backend you can access the values of properties, first
, middle
, last
, using POST as array. For Php we can write –
$_POST[‘name‘][‘first‘]
$_POST[‘name‘][‘middle‘]
$_POST[‘name‘][‘last‘]