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)
)
Community
  • 1
  • 1
erik
  • 3,810
  • 6
  • 32
  • 63

2 Answers2

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")));
GBD
  • 15,847
  • 2
  • 46
  • 50
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){
},
}); 
Aman Chhabra
  • 3,824
  • 1
  • 23
  • 39