Sending multidimensional json object to the server (PHP) but it is not possible to send a multidimensional json object here is my code:
DOJO code:
var ObjArry=[];
var test1 = {key:value, key:value, key:value, key:value};
var test2 = {key:value, key:value, key:value, key:value};
ObjArry.push(dojoJson.toJson(test1 ,true));
ObjArry.push(dojoJson.toJson(test2 ,true));
request.post("services/service.php?where=saveObj",{
data: ObjArry,
handleAs: "json",
sync: true,
timeout:13000,
headers: { "Content-Type": "application/json", "Accept": "application/json" }
}).then(function(data){
console.log(data); //output - null
});
Server side (PHP) code:
//saveObj is php function
function saveObj(){
print_r($_POST);
}
And the output I get is:
Array()
After looking closer to your Dojo code, I noticed a few things, the functions dojo::toJson
and dojo::fromJson
are deprecated in favour of dojo/json::stringify
and dojo/json::parse
, similar to how the JSON
object works.
Just like @Mike Brant said in his answer, you will have to use it on the entire array, for example:
ObjArray = dojoJson.stringify([ test1, test2 ]);
Then the request works properly, however, it indeed sends an empty request body. After removing the following header:
Accept: application/json
it started to work though, so I suggest removing it from your request, then it should work as you can see in this example: http://jsfiddle.net/DgTLC/ (it sends a 404, but there is a request payload).
About your PHP I'm not sure either if you can use $_POST
to retrieve the post body, according to this answer you could use:
$data = json_decode(file_get_contents('php://input'), true);
You need to JSON-encode ObjArry after you have added elements to the array.
ObjArry.push(test1);
ObjArry.push(test2);
json = dojoJson.toJson(ObjArry);
Then pass json in Ajax call.