-1

I'm sending data to the server as follow:

$scope.saveCaption = function(user_id) {
  var target = document.getElementById('toRender');
      html2canvas(target, {
        onrendered: function(canvas) {
    $http({
      url: "/production/save.php?user_id="+user_id,
      method: "POST",
      headers: {
        'Content-type': 'application/x-www-form-urlencoded'
      },
      data: {
        //image: canvas.toDataURL("image/png"), // commented out for testing only
        news: 'test'
        }
    }).success(function(data, status, headers, config) {
      console.log('success');
      $scope.data = data;
    }).error(function(data, status, headers, config) {
      console.log('failed');
      $scope.status = status;
    });
  }});
}

And trying to read it with PHP - save.php:

$data = $_POST['news'];
echo "data is $data"; die;

The problem is that $_POST['news'] is always blank?

This is the data sent:

{"news":"test"} 

Notice it's JSON, yet I specifically tried to change the content type:

'Content-type': 'application/x-www-form-urlencoded'

So how can I send normal data as opposed to JSON? Or, how can I get the php to read the JSON properly, I tried $data = json_decode($_POST['news']) but that gives blank too

StudioTime
  • 22,603
  • 38
  • 120
  • 207
  • maybe decode the entire response first? before getting the array element. – Reuben L. Apr 04 '15 at 05:21
  • 1
    The $http service will not form urlencode your data out of the box. See: see: http://stackoverflow.com/questions/11442632/how-can-i-post-data-as-form-data-instead-of-a-request-payload – Joel Skrepnek Apr 04 '15 at 05:22
  • Alternatively, use the `php://input` stream and `json_decode` its contents. – Sacho Apr 04 '15 at 07:56

1 Answers1

1

You need to form encode the parameters in data:

$scope.saveCaption = function(user_id) {
  var target = document.getElementById('toRender');
      html2canvas(target, {
        onrendered: function(canvas) {
    $http({
      url: "/production/save.php?user_id="+user_id,
      method: "POST",
      headers: {
        'Content-type': 'application/x-www-form-urlencoded'
      },
      data: 'news=test', // form encoded
    }).success(function(data, status, headers, config) {
      console.log('success');
      $scope.data = data;
    }).error(function(data, status, headers, config) {
      console.log('failed');
      $scope.status = status;
    });
  }});
}
Peter Ashwell
  • 4,292
  • 2
  • 18
  • 22