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) {});
0

5 Answers 5

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.

Sign up to request clarification or add additional context in comments.

3 Comments

I was hoping you could take a look at stackoverflow.com/questions/34480438/… ? The problem I'm encountering is similar but has some distinct differences from the one posted in this thread.
Thanks. I was using the examples at 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: stackoverflow.com/questions/19254029/…
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 corpus.hubwiz.com/2/angularjs/19254029.html then now I successfully send the data to backend .
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);
}

Comments

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'; 
});

1 Comment

You should be cursing PHP
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.

1 Comment

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.
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.