0

I have the below code running to send data as a JSON object

var jdata = JSON.stringify(grid.serialize());
$.ajax({
    'type': 'POST',
    'url': 'print.php',
    'data': jdata, //assuming you have the JSON library linked.
    'contentType': "application/json",
    'success': function (data) {
        alert(data);
    },
    'error': function (x, y, z) {
        alert(x.responseText);
        // x.responseText should have what's wrong
    }
});
alert(JSON.stringify(grid.serialize()));

Currenty the alert after the ajax function prints

[{"id":"1","col":"1","row":"1","size_y":"1","size_x":"1"},{"id":"2","col":"2","row":"1","size_y":"1","size_x":"1"}]

On the receiving page I am using <?php print_r($_POST) ?> to see what the page is being sent and it keeps outputting

Array
(
)

I must be missing something simple but have been unable to figure out what. Maybe a fresh set of eyes will see a simple mistake I have made.

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
Somk
  • 11,869
  • 32
  • 97
  • 143

2 Answers2

2

I think $_POST is only populated if you send the data encoded as x-www-form-urlencoded. So, just assign the JSON string to a key (jQuery takes care of encoding it properly):

'data': {data: jdata}

and remove the 'contentType': "application/json" part.

Then you get the data in PHP with:

$data = json_decode($_POST['data'], true);

Alternatively, get the raw body of the request in PHP and process it: How to retrieve Request Payload

Community
  • 1
  • 1
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
  • I tried this method and it passes the json array but backsashes a of the double quotes – Somk May 18 '13 at 12:27
  • Then you should probably disable magic quotes: http://stackoverflow.com/questions/6642901/php-5-3-automatically-escapes-get-post-from-form-strings – Felix Kling May 18 '13 at 12:28
0

If you are sending JSON to the server, on the back-end grab your JSON using:

json_decode(file_get_contents('php://input'));

It won't be in the $_POST super global.

anomaaly
  • 833
  • 4
  • 15