I'm trying to pass data to php with jquery. I'm getting the data with javascript.
JQuery :
$.post("export.php", JSON.stringify(result)); //result is an array of object
When i'm using the debugger on chrome I can see something like this in form data: [{"id":"foo","x":0,"y":1,"z":8,"t":3}]:
But when I'm trying to retrieve this with php, it doesn't work :
echo 'Before decode ';
$array=$_POST['data'];
echo 'After decode ';
echo $array;
And it's echoing only this : Before decode After decode
What am I missing? (I know I should decode the data to get back an array in php, but I simplified it to see where the problem come from)
If you want to send an encoded JSON string and access it through $_POST['data']
you need to wrap the result in an object with key data
:
$.post("export.php", {data: JSON.stringify(result)});
Then in your server you can decode it like this:
echo 'Before decode ';
$array = json_decode($_POST['data']);
echo 'After decode ';
print_r($array);
try to post your json in data
variable then you will get $_POST['data']
on export.php
$.post("export.php", {data : result});
or you can use to get your posted data without variable with file_get_contents()
$data = file_get_contents('php://input');
and the decode it json_decode()
Typically you won't even have to transform the data into JSON:
$.post("export.php", { data: result });
Alternatively, you'd have to fish the JSON encoded body out from the input stream, ie:
$array = json_decode(file_get_contents('php://input'), true);
This typically happens if the content type of the request body is not advertised as application/x-www-form-urlencoded
.
When you post raw JSON data, PHP doesn't know how to decode it, and will not populate $_POST
. You have to parse it yourself. Untested, but try this:
print_r(
json_decode(
file_get_contents('php://input')
)
);
Note that since you are posting JSON, I highly recommend using $.ajax
instead so you can set contentType: 'application/json'
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.