14

The following $http request executes successfully, yet the PHP script on the other end receives an empty $_POST array when it should receive 'test' and 'testval.' Any ideas?

$http({
    url: 'backend.php',
    method: "POST",
    data: {'test': 'testval'},
    headers: {'Content-Type': 'application/x-www-form-urlencoded'}
    }).success(function (data, status, headers, config) {
    console.log(data);

    }).error(function (data, status, headers, config) {});
Lamloumi Afif
  • 8,941
  • 26
  • 98
  • 191
hawkharris
  • 2,570
  • 6
  • 25
  • 36

5 Answers5

18

If you wan to send just that simple data, try this:

$http({
    url: 'backend.php',
    method: "POST",
    data: 'test=' + testval,
    headers: {'Content-Type': 'application/x-www-form-urlencoded'}
    }).success(function (data, status, headers, config) {
        console.log(data);

    }).error(function (data, status, headers, config) {});

And php part shoul be like this:

<?php
    $data = $_POST['test'];
    $echo $data;
?>

It is working for me.

Gabor Kako
  • 198
  • 1
  • 6
  • I was hoping you could take a look at http://stackoverflow.com/questions/34480438/how-to-grab-php-data-from-angularjs ? The problem I'm encountering is similar but has some distinct differences from the one posted in this thread. – Zypps987 Dec 27 '15 at 18:20
  • Thanks. I was using the examples at https://docs.angularjs.org/api/ng/service/$http under `Shortcut methods`: `$http.get('/someUrl', config).then(successCallback, errorCallback);` `$http.post('/someUrl', data, config).then(successCallback, errorCallback);` The top answer on this question explains it well: http://stackoverflow.com/questions/19254029/angularjs-http-post-does-not-send-data – Gabri Botha Sep 07 '16 at 14:42
  • Hi All, in my condition changing only the headers was not enough to send the data . I also overrided transformRequest method like as pointed in the link http://corpus.hubwiz.com/2/angularjs/19254029.html then now I successfully send the data to backend . – katmanco Mar 17 '17 at 17:28
7

This is a common issue with AngularJS.

The first step is to change the default content-type header for POST request:

$http.defaults.headers.post["Content-Type"] = 
    "application/x-www-form-urlencoded; charset=UTF-8;";

Then, using an XHR request interceptor, it is necessary to serialize properly the payload object:

$httpProvider.interceptors.push(['$q', function($q) {
    return {
        request: function(config) {
            if (config.data && typeof config.data === 'object') {
                // Check https://gist.github.com/brunoscopelliti/7492579 
                // for a possible way to implement the serialize function.
                config.data = serialize(config.data);
            }
            return config || $q.when(config);
        }
    };
}]);

In this way, payload data will be again available in the $_POST array.

For more info about XHR interceptor.

Another possibility, it is to mantain the default content-type header, and then server side parse the payload:

if(stripos($_SERVER["CONTENT_TYPE"], "application/json") === 0) {
    $_POST = json_decode(file_get_contents("php://input"), true);
}
Bruno
  • 5,961
  • 6
  • 33
  • 52
7

More simplified way:

myApp.config(function($httpProvider) {
    $httpProvider.defaults.transformRequest = function(data) {        
        if (data === undefined) { return data; } 
        return $.param(data);
    };
    $httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8'; 
});
3

Remove the following line, and the preceding comma:

headers: {'Content-Type': 'application/x-www-form-urlencoded'}

And then the data will appear in $_POST. You only need that line if you are uploading a file, in which case you'll have to decode the body to get the data vars.

KGolding
  • 380
  • 1
  • 4
  • Thanks for your response. Unfortunately, I removed the line but didn't have any luck. The print_r($_POST) command in my PHP script is still returning an empty array. – hawkharris Oct 06 '13 at 21:07
2

I found my solution here http://www.peterbe.com/plog/what-stumped-me-about-angularjs. There is a piece of code in the "AJAX doesn't work like jQuery" section, which solved my problem.

notMyName
  • 685
  • 5
  • 3