I have the following json sent (POST) from my javascript to the php
function boardToJSON() {
return JSON.stringify({
"pieces" : gPieces, // gpieces and gdestinations is an array
"destinations" : gDestinations,
"boardSize" : kBoardHeight // boardSize is an integer value 9
});
// Below function is called on Button Click and url contains PATH to the php file.
function makeMove() {
var move;
$.ajax({
type: 'POST',
url: url,
contentType: "application/json",
dataType: "json",
async: false,
data: boardToJSON(),
success: function(msg) {
move = msg;
},
error: function(jqXHR, exception) {
if (jqXHR.status === 0) {
alert('Unable to connect.\n Verify Network.');
} else if (jqXHR.status == 404) {
alert('Requested URL of HalmaAI not found. [404]');
} else if (jqXHR.status == 500) {
alert('Internal Server Error [500].');
} else if (exception === 'parsererror') {
alert('Data from HalmaAI was not JSON :( Parse failed.');
} else if (exception === 'timeout') {
alert('Time out error.');
} else if (exception === 'abort') {
alert('Ajax request aborted.');
} else {
alert('Uncaught Error.\n' + jqXHR.responseText);
}
}
});
On the server side (in PHP) I am trying to get it like this
$jsonString = file_get_contents("php://input");
$myJson = json_decode($jsonString);
echo $myJson["boardSize"]; // also tried $myJson.boardSize etc
Issue is that I am unable to decode JSON in PHP. Can someone guide me here please ? Thanks
$_POSTsuperglobal is not json_encoded; only a child element in that array can be.$_POSTdoesn't come into play here. He is trying to read JSON from PHP raw input.