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 ?

7
  • 1
    what is in var_dump($tab1); Commented May 8, 2013 at 12:02
  • In fact I cannot see directy the PHP file, because $.post('save.php', info); doesn't redirect me. Commented May 8, 2013 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. Commented May 8, 2013 at 12:09
  • 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. Commented May 8, 2013 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 Commented May 8, 2013 at 12:16

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.