Reputation: 189
I want to send a array to php with this structure:
Array[0]['name'] = ...
Array[0]['def'] = ...
Array[1]['name'] = ...
Array[1]['def'] = ...
and so on....
To do this I have a multidimensional array object like this:
var allShapes = new Array();
$('.shape_name').each(function(index){
allShapes[index] = new Array();
allShapes[index]['name']=$(this).val();
allShapes[index]['def']=$(this).closest("tr").find('*[id*=shape_def_]').val();
});
I send it through a post request to php:
$.post("../some.php", {
'shape_defs' : allShapes
}, function() {
console.log(allShapes);
}, "json").success(function() {
console.log("success");
});
How do I have to iterate through thos array in php? Something goes wrong there......
The Array which comes as $_POST (after json_decode) has the following content:
[{"name":"Ta","def":"somestring"},{"name":"WSCall","def":"somestring"},{"name":"manual","def":"somestring"}]
How do I iterate to get the values of the keys?
Upvotes: 1
Views: 963
Reputation: 66304
A common misunderstanding when people move from PHP to JavaScript seems to be that they don't realise non-integer keys are not a standard part of Arrays in JavaScript. The reason the interpreter doesn't complain is because Array inherits Object and Object can use any String as a key.
If you try to Serialise a JavaScript Array with non-standard keys, you'll lose them entirely as they can't be written in the form of an Array literal.
Therefore, you should be creating Objects as the items of allShapes
, not Arrays.
var allShapes = []; // array literal
$('.shape_name').each(function (index) {
allShapes[index] = { // object literal
'name': $(this).val(),
'def': $(this).closest("tr").find('*[id*=shape_def_]').val()
};
});
Finally, convert the structure to JSON using JSON.stringify
var allShapesJSON = JSON.stringify(allShapes);
// send allShapesJSON..
Upvotes: 3
Reputation: 2173
Serializing your array using JSON.stringify and then parsing it in PHP using json_decode should fix your problem. Complex data structures generally don't transfer well without encoding them.
Upvotes: 2