10

When making an ajax call, when contentType is set to application/json instead of the default x-www-form-urlencoded, server side (in PHP) can't get the post parameters.
in the following working example, if I set the contentType to "application/json" in the ajax request, PHP $_POST would be empty. why does this happen? How can I handle a request where contentType is application/json properly in PHP?

$.ajax({
    cache: false,
    type: "POST",
    url: "xxx.php",
    //contentType: "application/json",
    processData: true,
    data: {my_params:123},
    success: function(res) {},
    complete: function(XMLHttpRequest, text_status) {}
});
1stthomas
  • 731
  • 2
  • 15
  • 22

4 Answers4

26
<?php
   var_dump(json_decode(file_get_contents('php://input')));
?>
Wrikken
  • 69,272
  • 8
  • 97
  • 136
2

You will find unrecognised MIME types in $HTTP_RAW_POST_DATA. You can also force PHP to always populate this array (not only for unrecognised MIME types) by setting the php.ini directive always_populate_raw_post_data to true.

Raw post data will otherwise be available through the input wrapper php://input

For more information:

http://us.php.net/manual/en/wrappers.php.php

http://php.net/manual/en/reserved.variables.httprawpostdata.php

http://www.php.net/manual/en/ini.core.php#ini.always-populate-raw-post-data

Ivar Bonsaksen
  • 4,747
  • 2
  • 32
  • 34
1

above is technically correct, but since I don't write much PHP, this might be more helpful

xxx.php would be

<?php
$file = fopen("test.txt","a");
$post_json = file_get_contents("php://input");
$post = json_decode($post_json, true);
foreach($post as $key=>$value) {
    $message = $key . ":" . $value . "\n";
    echo fwrite($file,$message);
}
fclose($file);
?>

and then you can test with

curl -X POST -H "Content-Type: application/json" -d '{"fieldA":"xyz","fieldN":"xyz"}' http://localhost/xxx.php
-1

If you have phalcon extension you can use getJsonRawBody ()

http://docs.phalconphp.com/en/latest/api/Phalcon_Http_Request.html

Handsome Nerd
  • 17,114
  • 22
  • 95
  • 173