ALR ALR - 2 years ago 90
JSON Question

Can't access JSON object sent to PHP via POST

I am sorry if this is a duplicate question. I have searched for an answer but nothing seems to work.

I am trying to send quite a large JSON object to a PHP file via POST.

This is my JavaScript code :

var grid =
"user": 1,
"grid": JSON.stringify(hz),
"week": WEEK,
"AP": AP,

grid = JSON.stringify(grid);

type: "POST",
data : "g="+grid,
success: function (data, textStatus, jqXHR)

This is my PHP code :

$g = stripslashes($_REQUEST["g"]);
echo $AP = $g->AP;

But this returns an error which says :

Trying to get property of non-object

What am I doing wrong?

Answer Source

Your primary problem is that you are trying to treat a string of JSON as if it were a PHP object.

You need to parse it first.

$g = stripslashes($_REQUEST["g"]);
$g = json_decode($g);
echo $AP = $g->AP;

You also have some secondary issues.

You failed to URL encode the JSON, so if it contains characters with special meaning in URLS, it will break.

data : "g="+grid,

should be:

data : { g: grid },

You should not need to run stripslashes over input from $_REQUEST/POST/GET.

If you don't have magic quotes turned on, then it could break the incoming data if it contains slashes.

If you do have magic quotes turned on, then you should turn them off or upgrade to a modern version of PHP (which wouldn't support them).

Nesting JSON inside JSON is silly. It bloats the data and makes it more work to read.

"grid": JSON.stringify(hz),

should be:

 grid: hz,

$_REQUEST could get data from the query string, or the request body, or a cookie. You know it is coming in the request body so just use $_POST to remove the ambiguity.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download