0

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 ?

Arnaud
  • 4,884
  • 17
  • 54
  • 85
  • 1
    what is in `var_dump($tab1);` – NullPoiиteя May 08 '13 at 12:02
  • In fact I cannot see directy the PHP file, because `$.post('save.php', info);` doesn't redirect me. – Arnaud May 08 '13 at 12:05
  • 1
    When I run this code $tab1 is 2. I had to add `var myTab1 = []; var myTab2 = [];` at the start of the Javascript. – George Hodgson May 08 '13 at 12:09
  • Oh, that's strange... Please how do you manage to read count($tab1) directly ? (me I put it on a database and then check the database but it's uncomfortable...) – Arnaud May 08 '13 at 12:11
  • 1
    If you are using firefox open your firebug on the "console" or "net" tab using the f12 key and check for XHR requests. If you are using chrome use the f12 key to open the developer tools and check the "network" tab. – jtavares May 08 '13 at 12:16
  • 1
    Use firebug you can use it to track your ajax requests and see the returned output of your code behind file so in your php you'd just echo or var_dump() as normal and use firebug to inspect the returned result. You're better off using a full blown ajax request with success/fail events too rather then just a blind post – Dave May 08 '13 at 12:16
  • Thank you, your help was very useful. My problem was finally not much related to my question. But this message was also useful : http://stackoverflow.com/a/6815562/2019761. – Arnaud May 08 '13 at 12:23

1 Answers1

3

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']);

jtavares
  • 449
  • 2
  • 9