Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angularjs $http POST request empty array

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) {});
like image 515
hawkharris Avatar asked Oct 06 '13 21:10

hawkharris


2 Answers

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.

like image 190
Gabor Kako Avatar answered Oct 14 '22 07:10

Gabor Kako


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);
}
like image 34
Bruno Avatar answered Oct 14 '22 08:10

Bruno