0

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

10
  • 1
    I don't get it. You say you're posting the JSON, but the PHP you show is attempting to load the JSON from a file, not receive it from POST. Commented Oct 21, 2014 at 20:12
  • 2
    @Utkanos that is the raw post body... Commented Oct 21, 2014 at 20:12
  • 1
    @AbraCadaver because the entire $_POST superglobal is not json_encoded; only a child element in that array can be. Commented Oct 21, 2014 at 20:18
  • 1
    then $myJson = json_decode($_POST['child']); Commented Oct 21, 2014 at 20:20
  • 1
    @SetSailMedia $_POST doesn't come into play here. He is trying to read JSON from PHP raw input. Commented Oct 21, 2014 at 20:21

2 Answers 2

1

You should set the contentType property on AJAX request to application/json. This will set proper header on request such that server will not attempt to populate $_POST in favor of you working with the raw input.

function makeMove() {
    var move;
    $.ajax({
        type: 'POST',
        url: url,
        contentType: "application/json"
        dataType: "json",
        async: false,
        data: boardToJSON(),
        success: function(msg) {
            move = msg;     
        }
    });
}

Assuming this works, you can access the boardSize property at:

$myJson->boardSize;

The other problem you have is that since you specify dataType: "json" you need to make sure you send back valid JSON, which you currently are not.

This is not valid JSON:

echo $myJson["boardSize"];

This would be (of course this is a trivial example):

$returnObj = new stdClass();
$returnObj->boardSize = $myJson->boardSize;
echo json_encode($returnObj);
Sign up to request clarification or add additional context in comments.

10 Comments

Now how can I get value of boardSize on the server side ??
No it says the data returned is not Json.
On Server Side I am going this. $jsonString = file_get_contents("php://input"); $myJson = json_decode($jsonString); $returnObj = new stdClass(); $returnObj->boardSize = $myJson->boardSize; echo json_encode($returnObj);
@farhangdon And what result do you get?
Json returned in Not Valid .
|
0

If you want decode json to array in PHP, you should set the 2nd argument of json_decode to true.
Example:

$jsonString = file_get_contents("php://input");
$myJson = json_decode($jsonString, true);
echo $myJson["boardSize"];

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.