How to send form parameters instead of JSON in angular?

1

I'm trying to send a POST via angular, just like I did in JQuery , however, when trying to capture the data via $_POST variable, it's not bringing any value.

I'm running a code similar to this in angular :

$http.post('/users/ajax-create', user).then(...);

The angle appears to be sending the data without the formatting required for PHP to process the parameters for the $_POST variable.

I can only get the values if I do this:

 json_decode(file_get_contents('php://input'), true);

But the above behavior is not desired. I would like to use angularjs in my php application, however I would not like to rewrite it or start doing different things just because of that angular

Is there any way to send the data of a javascript object by angular , but as parameters of a form form-url-encoded ?

Note: If this is a standard angular behavior, I would not want to be writing any code to each project that I implemented the angle. So if there is any library ready to convert the data to form-url-encoded , I'll be happy if there is an indication.

    
asked by anonymous 06.07.2016 / 16:23

2 answers

3

You can use the $httpParamSerializer service to modify an object and prepare it for submission, in conjunction with a specific header indicating the form-urlencoded type.

$scope.submitForm = function(data) {
  $http({
  method  : 'POST',
  url     : 'process.php',
  data    : $httpParamSerializer(data),
  headers : { 'Content-Type': 'application/x-www-form-urlencoded' }  // Necessário para especificar o tipo de conteúdo
 })
  .then(function(data) {
  });
};

Sources:
 - link
 - link

    
06.07.2016 / 16:53
3

You need to pass the Content-Type: application/x-www-form-urlencoded header on the request, in addition to rewriting the request body so that a JSON is not transmitted.

So, in the $http method do so:

$http({
    method: 'POST',
    url: url,
    headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
    },
    transformRequest: function(obj) {
        var str = [];
        for (var p in obj) {
            str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
        }
        return str.join("&");
    },
    data: xsrf
});
    
06.07.2016 / 16:33