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 ?

1 Answer 1

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

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

6 Comments

Why does Chrome say [2: Object] I thought it was an object which consisted of arrays inside of it ?
It says so because, it is an array with only one element whose index is 2 and value is a JS object.
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
cleaning out the empty array elements would depend on structure expected. If specific indexes are expected in php would cause problems
So PHP would not be happy with 6: Array[0] length: 0 ?
|

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.