Reputation: 189
Another json related question unfortunately...
Consider the following json
[{"details":{
"forename":"Barack",
"surname":"Obama",
"company":"government",
"email":"[email protected]",
"files": [{
"title":"file1","url":"somefile.pdf"
},
{
"title":"file2",
"url":"somefile.pdf"
}]
}
}]
I need to send this data to a php script on my server and then interact with it on the server but don't know how.
I'm sending it via jquery.ajax and its being sent fine (no error messages) and heres the code. (newJson is my json object I've created exactly as above)
$.ajax({
type: "POST",
url: "test.php",
dataType: 'json',
data: newJson,
success: function(msg)
{
alert(msg);
},
error: function(jqXHR, textStatus)
{
alert(textStatus);
}
});
So in my php script so far I just want to echo back the content as a string which displays in the success alert
<?php
header('Access-Control-Allow-Origin: *');
echo $_POST;
?>
but that just gives me a parse error.. so any ideas you wonderful people?
Upvotes: 0
Views: 6097
Reputation: 171698
You have to have a key/value pair to receive the data in php with $_POST[key]
. Sending the array you have all by itself is not best approach since you already have structure to object
I would unwrap the outer array, since you are only sending one object inside it
Then Object would look like
{"details":{
"forename":"Barack",
"surname":"Obama",
"company":"government",
"email":"[email protected]",
"files": [{
"title":"file1","url":"somefile.pdf"
},
{
"title":"file2",
"url":"somefile.pdf"
}]
}
}
In php would receive with $_POST['details']
. Don't convert to JSON, just pass the whole object to $.ajax data
property.
If you get parserror
from ajax, is on receiving side and sounds like either getting a 500 eror from php or not sending back json as expected by your dataType
Upvotes: 2
Reputation: 36
First, the original JSON string is of wrong format. Try
{
"details":{
"forename":"Barack",
"surname":"Obama",
"company":"government",
"email":"[email protected]",
"files": [
{ "title":"file1","url":"somefile.pdf" },
{ "title":"file2","url":"somefile.pdf"}
]
}
}
Second, the data sent to PHP has already parsed into an array, but not in JSON. To echo, you must use json_encode to convert the array back to JSON string
echo json_encode($_POST);
exit;
Upvotes: 1
Reputation: 1272
Since you are not passing the JSON as a field, you can do:
<?php
$post = file_get_contents("php://input");
$json = json_decode($post);
var_dump($json); // Should be a nice object for you.
Upvotes: 0