Arnaud
Arnaud

Reputation: 5122

Post an object of arrays of objects (jQuery/PHP)

I'm looking for a way to post an object of arrays of objects in jQuery to a PHP file, and to decode it.

What I've tried :

jQuery

myTab1[0] = {a: 2, b: 3};
myTab1[1] = {a: 1, b: 1};
myTab2[0] = {a: 42, b: 43};
myTab2[1] = {a: 15, b: 17};
var info = {id: 57,
            title: 'myTitle',
            tab1: JSON.stringify(myTab1),
            tab2: JSON.stringify(myTab2)
           };
$.post('save.php', info);

PHP

$tab1 = json_decode($_POST['tab1'])
echo count($tab1); // always 1, whatever myTab1

Have you an idea please ?

Upvotes: 0

Views: 6835

Answers (1)

jtavares
jtavares

Reputation: 449

Make sure you are using count on something that is an array, by your code it seems you are counting the result of json_decode wich is an object. using count there will not work as intended.

note that PHP as a little problem with count on something that is false: if you do count(false) it will return "1" so make sure you are counting something that exists and is an array.

also, try using the second parameter to specify you want and array by passing "true"

$tab1 = json_decode($_POST['tab1'],true);

Or cast it as array as you decode

$tab1 = (array)json_decode($_POST['tab1']);

Upvotes: 3

Related Questions