First of all I apologize for my bad English.
I did something to get the data properly on the server side, not when I was writing to the console. I hope you want to do this.
I had to write a javascript function to get the client side nested data on the server side.
For this I wrote the obj2FormData() function. Square brackets seem to work.
function obj2FormData(obj, formData = new FormData()){
this.formData = formData;
this.createFormData = function(obj, subKeyStr = ''){
for(let i in obj){
let value = obj[i];
let subKeyStrTrans = subKeyStr ? subKeyStr + '[' + i + ']' : i;
if(typeof(value) === 'string' || typeof(value) === 'number'){
this.formData.append(subKeyStrTrans, value);
} else if(typeof(value) === 'object'){
this.createFormData(value, subKeyStrTrans);
}
}
}
this.createFormData(obj);
return this.formData;
}
When sending data with Ajax, we convert the nested object to the FormData object.
let formData = obj2FormData({
name : 'Emrah',
surname : 'Tuncel',
birth: 1983,
child : {
name: 'Eylul',
surname: 'Tuncel',
toys: ['ball', 'baby']
},
color: ['red', 'yellow']
});
Now let's send the FormData that we transformed with ajax.
const xhr = new XMLHttpRequest();
xhr.addEventListener('load', response => {
//AJAX RESPONSE >>
console.log(response);
//AJAX RESPONSE //
});
xhr.open('POST','response.php');
xhr.send(formData);
When I pressed the data to the screen with PHP, I got the exact result I wanted. It doesn't matter whether the method is POST or GET.
response.php
<pre><? print_r($_GET) ?></pre>
<pre><? print_r($_POST) ?></pre>
The output was as follows.
Array
(
[name] => Emrah
[surname] => Tuncel
[birth] => 1983
[child] => Array
(
[name] => Eylul
[surname] => Tuncel
[toys] => Array
(
[0] => ball
[1] => baby
)
)
[color] => Array
(
[0] => red
[1] => yellow
)
)
Hopefully it benefits your business.
key[subkey]notation, e.gformData.append('preview[p_title]', 'p title');. But otherwise, simply send it as a JSON string and parse it server side, usually the simplest both to send and retrieve.