0

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()
g00glen00b
  • 41,995
  • 13
  • 95
  • 133
Tushar Kadam
  • 173
  • 1
  • 1
  • 9
  • 2
    How are you logging your server-side output? – Cerbrus Jun 23 '14 at 10:00
  • I have just added following function in php: public function saveObj($item) { print_r($item); } – Tushar Kadam Jun 23 '14 at 11:15
  • Adding code in the comments is not a good idea, please edit your question. Also, this is not the entire code, how is `saveObj()` called and what is `$item` (what does it contain)? There's no problem with the Dojo code, so we should be looking at the PHP code. – g00glen00b Jun 23 '14 at 11:47
  • Thanks for replay, In PHP I have just print posted data from dojo but there is empty array. – Tushar Kadam Jun 24 '14 at 05:20

2 Answers2

0

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.

Mike Brant
  • 70,514
  • 10
  • 99
  • 103
0

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);
Community
  • 1
  • 1
g00glen00b
  • 41,995
  • 13
  • 95
  • 133