Last Updated: February 25, 2016
·
7.299K
· rmcdaniel

Making PHP's $_POST Work With AngularJS's $http

If you try to do something like this in AngularJS:

$http.post('api.php', {password: 'test123'});

You might be puzzled when the following PHP code doesn't produce any output:

echo $_POST['password'];

The reason why this fails is because PHP expects a content-type and format of "application/x-www-form-urlencoded" but that is not what $http sends by default. The fix only requires the following addition to your main application module's config.

$httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8';

var param = function(obj) {
    var query = '',
        name, value, fullSubName, subName, subValue, innerObj, i;

    for (name in obj) {
        value = obj[name];

        if (value instanceof Array) {
            for (i = 0; i < value.length; ++i) {
                subValue = value[i];
                fullSubName = name + '[' + i + ']';
                innerObj = {};
                innerObj[fullSubName] = subValue;
                query += param(innerObj) + '&';
            }
        }
        else if (value instanceof Object) {
            for (subName in value) {
                subValue = value[subName];
                fullSubName = name + '[' + subName + ']';
                innerObj = {};
                innerObj[fullSubName] = subValue;
                query += param(innerObj) + '&';
            }
        }
        else if (value !== undefined && value !== null) query += encodeURIComponent(name) + '=' + encodeURIComponent(value) + '&';
    }

    return query.length ? query.substr(0, query.length - 1) : query;
};

$httpProvider.defaults.transformRequest = [function(data) {
    return angular.isObject(data) && String(data) !== '[object File]' ? param(data) : data;
}];

You can see how this is used by the angular-codeigniter-seed project at: https://github.com/rmcdaniel/angular-codeigniter-seed/blob/master/js/application.js#L30

2 Responses
Add your response

Thanks man, simple first solution I found!

Congratulations.

over 1 year ago ·

I implemented this solution today and it fixed my issue, but only when dealing with simple objects (e.g., {...}), not arrays of simple objects (e.g., [{...},{...},{...},{...}]).

When passing only a simple object, my back-end .NET API is able to parse what I give it. When it's expecting an array or List<T> of simple objects, and I pass an array through this mechanism, it's not able to parse what I provide.

Thanks!

over 1 year ago ·