Suppose I have the following data:
var arr = [], arr1 = [], arr2 = [], arr3 = [], arr4 = [];
var a = 'something', b = 'else';
arr1['key1-1'] = 'value1-2';
arr1['key1-2'] = 'value1-2';
for (var i = 0; i < someCond; i++) {
arr = [];
arr['key2-1'] = 'value2-1';
arr['key2-2'] = 'value2-2';
arr2.push(arr);
}
Now I need to pass the hole of it to a php script.
I packaged it into a single variable like so:
var postVar = {
a: a,
b: b,
arr1: arr1,
arr2: arr2
};
I’m using jQuery so I tried to post it like this:
1)
//Works fine for a and b, not for the arrays
$.post('ajax.php', postVar, function(response){});
and this:
2)
var postVar = JSON.stringify(postVar);
$.post('ajax.php', {json: postVar}, function(response){});
with the php file
$req = json_decode(stripslashes($_POST['json']), true);
which also doesn’t work.
How should I structure/format my data as to send it to PHP?
Thanks
EDIT:
Case 1:
console.log(postVar);

PHP print_r($_POST) response:
Array
(
[a] => something
[b] => else
)
As you can see, there are no arrays (objects) on the php side.
Case 2:
When I add the following:
postVar = JSON.stringify(postVar);
console.log(postVar);
I get
{“a”:”something”,”b”:”else”,”arr1″:[],”arr2″:[[],[],[]]}
with console.log(postVar)
So that seems to be the problem in this case… right?
As it turns out, although Arrays are Objects, JSON.stringify ignores non Array properties on Arrays. So I had to explicitly declare all variables as objects. Except for arr2 that is really used as an array.
Here goes the full code:
And on the PHP side:
Hope this helps others with the same problem.