0

I'm quite new to angular.js. Now I try to post some data to a PHP-Script.

angular.js:

var app = angular.module('app', []);
app.controller('sendData', function($scope, $http) {
    $http.post("script.php", {'value': 'one'} )
    .success(function (response) {
        console.log(response);
    });
});

PHP:

$data = json_decode(file_get_contents("php://input"));

So I would get the data in $data->value.

Is it possible to modify the script (without using $.param of JQuery), so I could access the post-data with $_POST['value'] - as I would normally do that in PHP?

user3142695
  • 15,844
  • 47
  • 176
  • 332

1 Answers1

1

$_POST is for using application/x-www-form-urlencoded or multipart/form-data as the HTTP Content-Type in the request

See: http://php.net/manual/en/reserved.variables.post.php

So, in order to use x-www-form-urlencoded (and $_POST), you must serialize your data properly whether you are using the $.param function or another serialize method.

This is how we do it, although like I said, you can use a different function than $.param if you need to.

$http({
  method: "post",
  url: url,
  data: $.param(data),
  headers: {'Content-Type': 'application/x-www-form-urlencoded'}
})

Here is a vanilla js method of serialization: https://stackoverflow.com/a/1714899/580487

Community
  • 1
  • 1
tommybananas
  • 5,718
  • 1
  • 28
  • 48