I am grappling with the task of creating a multidimensional array in JavaScript to send data via an Ajax call to PHP. My expertise in JS is limited, especially when it comes to this particular task...
I have shared the code on JSFiddle
The desired structure of the array should be like this:
var data = {
bewaarnaam: 'bewaarnaam!',
rows: [{
row_1: [{
name: 'Row Name 1',
x: 450,
y: 250,
chest1: [{
counter: 1,
height: 5
}],
chest2: [{
counter: 2,
height: 3
}]
}],
row_2: [{
name: 'Row Name 2',
x: 650,
y: 550,
chest1: [{
counter: 1,
height: 8
}],
chest2: [{
counter: 2,
height: 4
}]
}],
}]
};
This is the JavaScript code snippet I am using to generate the object array:
function saveThis() {
var bewaarNaam = $("#bewaarplaatsName").val();
hide_overlay_save_name();
log("now where going to save everything with the name: " + bewaarNaam);
var dataRows = [{
'bewaarnaam': bewaarNaam
}];
$(".rows").each(function (i, obj) {
var row = $(obj);
var rowName = $(row).attr('name');
var chests = [];
$(".cv_chest", row).each(function (i2, obj2) {
chests[$(obj2).attr('id')] = [{
'counter': $(obj2).attr('chest_counter'),
'height': $(obj2).attr('chest_height')
}];
});
var rowData = [{
rowName: [{
'name': $(row).attr('name'),
'x': $(row).css('left'),
'y': $(row).css('top'),
'chests': chests
}]
}];
dataRows[$(row).attr('id')] = rowData;
});
log(dataRows);
log("sending data with ajax...");
$.ajax({
type: 'post',
cache: false,
url: '{{ url('
bewaarplaatsen / nieuw ') }}',
data: dataRows
}).done(function (msg) {
log("ajax success");
log(msg);
}).fail(function (msg) {
log("ajax error");
log(msg);
});
}
Upon inspecting the variable dataRows
, the output looks like this:
[Object, row_1: Array[1], row_2: Array[1]]
0: Object
bewaarnaam: "Bewaar Naam!"
__proto__: Object
length: 1
row_1: Array[1]
0: Object
...
Further analysis by executing the code confirms that the object is properly structured as intended:
{
"bewaarnaam": "Bewaar Naam!",
"rows": [{
"row_1": [{...}],
"row_2": [{...}]
}]
}
However, when examining the POST
value in PHP, it shows just [undefined]
. Additionally, the Chrome debug tool reveals two undefineds
under Form Data
:
Form data
undefined:
undefined:
It appears that the object is not being created correctly, causing issues when sending it via Ajax and rendering the post data unusable in PHP.
Hence, my question boils down to identifying the misstep in my approach and finding a solution to rectify the problem.