2

I hesitate to ask, as there are numerous other posts on this topic (one and two for example), but none of the solutions in those posts seem to apply to me.

I am trying to pass a JSON-encoded object from a page to a PHP controller, and then respond back with some information.

If I watch in Firebug, I can see the object being sent under the 'Post' tab, however when I print out the $_GET, $_POST, and $_REQUEST arrays I see nothing at all regarding the json object. The $_GET array at least shows my querystring of 'update-player', however POST is empty and REQUEST only shows some local cookies I have.

Here is my jQuery code. As you can see I'm hardcoding the JSON at the moment, and the intention is that I will have a jQuery method updating the local object.

function sendPlayerUpdate(row, col) {
    var playerinfo = [
        {
          "id": 1,
          "row": row,
          "col": col
        }
      ];

        alert(playerinfo[0].id); //debugging

    $.ajax({
        type: 'POST',
        url:"controller.php?a=update-player",
        //data: $.toJSON(playerinfo[0],
        data: { json: JSON.stringify(playerinfo) },
        contentType: "application/json",
        success: function (){

        },
        dataType: 'json'
      });
 };

My corresponding PHP code handling the request:

// update player information from AJAX POST
case "update-player":
  if (isset($_POST['json'])) echo "json received\n\n";
  else echo "json not received\n\n";
  echo "GET VARIABLES\n";
  print_r($_GET);
  echo "\n\nPOST VARIABLES\n";
  print_r($_POST);
  echo "\n\nREQUEST VARIABLES\n";
  print_r($_REQUEST);

And, what I see in Firebug:

Firebug output json not received

GET VARIABLES
Array
(
    [a] => update-player
)


POST VARIABLES
Array
(
)


REQUEST VARIABLES
Array
(
    [a] => update-player
    (local cookies)
)

2 Answers 2

5

Try in PHP as below (When request is an application/json, then you will not get data into $_POST)

var_dump(json_decode(file_get_contents("php://input")));
Sign up to request clarification or add additional context in comments.

2 Comments

due to application/json, your json passing in body request
ahhh, makes sense...so i can just pull that into a local object and work from there. thanks!
0

Try this May be it will work for you

 $.ajax({
type: 'POST',
url:"controller.php?a=update-player",
data: data_json=JSON.stringify(playerinfo),
success: function (data){
},
}); 

3 Comments

Tried that, however the $_POST array is still empty.
can you please again post the PHP code and have you used $_POST['data_json']?
See accepted answer...I'm just going to read from the raw input data. Thanks though!

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.