I have a multidimensional array in JavaScript and I need to send it to a PHP script.
Below is what I am doing to send the data at present but it's sending blank data.
I've narrowed it down to what I'm logging in the image.
Is there another way to send this or why is JSON.stringify appearing blank?
console.log(results);
console.log(JSON.stringify(results));
var form_data = new FormData();
form_data.append("results", JSON.stringify(results));
fetch('myfile.php', {
method: 'POST',
body: form_data
})
var response_object = {"1": response1, "2": response2};
var test_object = {[current_test]: response_object};
var section_object = {[current_section]: test_object};
results = { ...results, ...section_object }
this is because you are not adding elements to array but only attaching properties to it, like 'section1'
and 'test1'
, you should instead declare those properties on some objects then insert those object into array, see in the example below what happens and how you could avoid that:
let result = [];
// BAD
result['section1'] = [];
result['section1']['test1'] = [, "2", "3"];
result['section1']['test2'] = [, "4", "5"];
result['section2'] = [];
result['section2']['test1'] = [, "2", "3"];
result['section2']['test2'] = [, "4", "5"];
console.log('BAD', JSON.stringify(result));
// GOOD
result = [{
'section1': [
{'test1': [, "2", "3"]},
{'test2': [, "4", "5"]}
]
}, {
'section2': [
{'test1': [, "2", "3"]},
{'test2': [, "4", "5"]}
]
}];
console.log('GOOD', JSON.stringify(result));