1

From UI I make call:

$http.post('services/loadCategory.php', {
    'id'    :'1',
    'type'  :'string'
}).then(function(response) {
    debugger;
    ...
}, function(response) {             
    ...
});

On PHP service I can't get variables from body POST request:

include ("bd.php");
header("Content-type: text/html; charset=windows-1251");
// ----- ----- ----- ----- -----
if (isset($_POST['type'])) {
    $type = $_POST['type'];
}
if (isset($_POST['id'])) {
    $id = $_POST['id'];
}   
//
exit(json_encode(
    array('type' => iconv('windows-1251', 'UTF-8', $_POST['type']), 
          'id' => iconv('windows-1251', 'UTF-8', $_POST['id'])
)));

Request from service: { id:'', type:'' } How fix that?

Darien Fawkes
  • 3,023
  • 7
  • 24
  • 35

2 Answers2

2

When posting JSON to PHP, the $_POST variable is empty. To get the raw JSON in your PHP, use the following:

if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
    $data = json_decode(file_get_contents('php://input'), true);
}

You can then access the data with $data['id'] and $data['type']

Check the incoming $data with print_r($data);

buzzsaw
  • 1,476
  • 1
  • 10
  • 14
  • Working)). Bit I do not understand - why simple $_POST do not work? – Darien Fawkes Oct 17 '15 at 22:06
  • @DarienFawkes This is because most front end setups, like jQuery, transmit POST data using Content-Type: x-www-form-urlencoded and the common ?key1=foo&key2=bar serialization. AngularJS uses Content-Type: application/json and { "key1": "foo", "key2": "bar" }. While this is just as good, PHP doesn't know how to deal with this natively. – buzzsaw Oct 17 '15 at 22:30
0

After doing a quick search about this issue, it appears that PHP has a hard time deserializing the POST body sent by AngularJS. AngularJS sends all information JSON encoded (application/json) as compared to most other JavaScript variants which send the content as application/x-www-form-urlencoded.

To fix this, you should either set the content-type of your request to application/x-www-form-urlencoded or you can try one of the solutions below which came from a similar question.

Based on this question, it would seem that the following code (provided by Felipe Miosso) seems to solve the problem:

  // Your app's root module...
  angular.module('MyModule', [], function($httpProvider) {
  // Use x-www-form-urlencoded Content-Type
  $httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8';

  /**
   * The workhorse; converts an object to x-www-form-urlencoded serialization.
   * @param {Object} obj
   * @return {String}
   */ 
  var param = function(obj) {
    var query = '', name, value, fullSubName, subName, subValue, innerObj, i;

    for(name in obj) {
      value = obj[name];

      if(value instanceof Array) {
        for(i=0; i<value.length; ++i) {
          subValue = value[i];
          fullSubName = name + '[' + i + ']';
          innerObj = {};
          innerObj[fullSubName] = subValue;
          query += param(innerObj) + '&';
        }
      }
      else if(value instanceof Object) {
        for(subName in value) {
          subValue = value[subName];
          fullSubName = name + '[' + subName + ']';
          innerObj = {};
          innerObj[fullSubName] = subValue;
          query += param(innerObj) + '&';
        }
      }
      else if(value !== undefined && value !== null)
        query += encodeURIComponent(name) + '=' + encodeURIComponent(value) + '&';
    }

    return query.length ? query.substr(0, query.length - 1) : query;
  };

  // Override $http service's default transformRequest
  $httpProvider.defaults.transformRequest = [function(data) {
    return angular.isObject(data) && String(data) !== '[object File]' ? param(data) : data;
  }];
});

Alternatively, you might be able to fix this problem by adding the following line of code to your PHP:

$params = json_decode(file_get_contents('php://input'),true);
Community
  • 1
  • 1
Spencer D
  • 3,376
  • 2
  • 27
  • 43