How to recover data sent from a post request at angular

Asked

Viewed 1,014 times

3

I’m making a post request for a php file that requires some data that is sent by the request. My question is how to retrieve this information that is being sent in the request

My requisition code is like this:

//pego a descricao no compa input
var dados = {"descricao": $('#descricao').val()};

$scope.getData = function() {
    $http.post('data.php', dados).success(function(data) {
        ...
        console.log(data);
    }).error(function(data) {
        ...
        console.log(data);
    });

How would you get this information in the data.php file'?

var_dump($_POST); returns an empty array: array(0) { }

  • @Sergio, I found a solution. I did so: $data = file_get_contents("php://input");

2 answers

4


The solution is as follows:

$post = file_get_contents("php://input");
$json = json_dencode($post);

2

Another way out would be this:

//pego a descricao no compa input
var dados = {"descricao": $('#descricao').val()};

$scope.getData = function() {
  $http.post('data.php', dados).success(function(data) {
    ...
    console.log(data);
  }).error(function(data) {
      ...
     console.log(data);
  }).config(['$httpProvider',function($httpProvider){
    $httpProvider.defaults.transformRequest.push(
            function(data){
                var requestStr;
                if (data) {
                    data = JSON.parse(data);
                    for (var key in data) {
                        if (requestStr) {
                            requestStr += '&' + key + '=' + data[key];
                        }else{
                            requestStr = key + '=' + data[key];
                        }
                    }
                }
                return requestStr;
            }
        );
    $httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'; 
}]);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.