0

I have a problem with sending an object in PHP. I stringify the object before sending it to the PHP file.

The PHP file then uses json_decode. But the decode shows a blank variable.

The object which i console.log shows this as its structure:

enter image description here

Its then sent to PHP with this :

    console.log(my_Obj);
    var as = JSON.stringify(my_Obj);        
    call_data('add.php?&as='+as, nxtFunc);  

Now in the PHP file i have this which handles the situation:

    $path = json_decode($_GET['as']);
    echo $_GET['as'].'<br/>';
    print_r($path);
    die;

The result is:

[null,null,{\"8\":[null,null,null,null,null,null,[],[],[],[],[]],\"9\":
[null,null,null,null,null,null,null,null,null,null,[]],\"10\":
[null,null,null,null,null,null,null,null,null,null,[],[]],\"11\":
[null,null,null,null,null,null,null,null,null,null,null,[]]}]   
<br/>

My XHR request url in Chrome shows:

add.php?as=[null,null,{%228%22:[null,null,null,null,null,null,[],[],[],[],[]],%229%22:[null,null,null,null,null,null,null,null,null,null,[]],%2210%22:[null,null,null,null,null,null,null,null,null,null,[],[]],%2211%22:[null,null,null,null,null,null,null,null,null,null,null,[]]}]

Notice the print_r shows nothing. Should i not be using stringify ?

Sir
  • 8,135
  • 17
  • 83
  • 146

1 Answers1

1

Thats because my_Obj is an array and not an object.

Try this:

var as = JSON.stringify({data: my_Obj});

Note:

You will also need to clean up the array before stringifying - i.e. clear out all null/undefined indices. Check this answer: https://stackoverflow.com/a/281335/921204

Community
  • 1
  • 1
techfoobar
  • 65,616
  • 14
  • 114
  • 135
  • Why does Chrome say `[2: Object]` I thought it was an object which consisted of arrays inside of it ? – Sir Dec 30 '12 at 03:06
  • It says so because, it is an array with only one element whose index is 2 and value is a JS object. – techfoobar Dec 30 '12 at 03:09
  • Wait how come i have to remove the blank ones? For example why is this not allowed: `[2: Object] 2: Object -> 8: Array[11] -> 6: Array[0] length: 0` – Sir Dec 30 '12 at 03:12
  • cleaning out the empty array elements would depend on structure expected. If specific indexes are expected in php would cause problems – charlietfl Dec 30 '12 at 03:15
  • So PHP would not be happy with `6: Array[0] length: 0` ? – Sir Dec 30 '12 at 03:17
  • You can clear it out in such a way that the indices are not changed, only the empty ones removed. And in PHP check it like `isset(a[x])` and so on. – techfoobar Dec 30 '12 at 03:30