简体   繁体   中英

file_get_contents(“php://input”) empty after ajax post

I'm hesitating to ask, but I haven't found any solution. After send data in php file in ajax function, when I try to catch the data in php file, the data are lost. But, yester I maked a similar function who run without problem. This is the ajax part:

$http({  
          url: 'PDO/Companion.php',
          data: {
              Companion : Companion,
              Companion : statut
          },
          method: 'POST',
          headers : {'Content-Type':'application/x-www-form-urlencoded; charset=UTF-8'}


      }).then(function (response) {// on success
          $scope.name=undefined;
          $http.get('js/controller/upPartenaire.php').success(function(data) {
              $scope.result = data;
              console.log(data);
          }), function(msg){
              console.log("ça")
              alert(msg);
          };

And the php part:

$postdata = file_get_contents("php://input");
$request = json_decode($postdata);
echo json_encode($request);

In my project I use PHP only for the ajax part to do SQL queryI also to catch data with $_POST but nothing

You need to set the content type to json and make JSON stringify like

$http({  
      url: 'PDO/Companion.php',
      data: JSON.stringify({
          Companion : Companion,
          Companion : statut
      }),
      method: 'POST',
      headers : {'Content-Type':'application/json; charset=utf-8'}


  }).then(function (response) {// on success
      $scope.name=undefined;
      $http.get('js/controller/upPartenaire.php').success(function(data) {
          $scope.result = data;
          console.log(data);
      }), function(msg){
          console.log("ça")
          alert(msg);
      };

This should help you. Consider changing php code:

header("Content-Type: application/json");

parse_str(file_get_contents('php://input', false , null, -1 , 
$_SERVER['CONTENT_LENGTH'] ), $postdata);

echo json_encode($postdata);

I have the same issue before My Solution i have convert the data into urlencoded format and pass into the post request.

url = Object.keys(data).map(function(k) {
    return encodeURIComponent(k) + '=' + encodeURIComponent(data[k])
}).join('&')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM