Make AngularJS requests work with PHP POST without refactoring PHP code

Whenever you are starting with AngularJS and PHP (or insert any other web framework here), one of the first things you will notice is that as soon as you want to post something with Angular's $http service, you will have to use a special "read" to get that data in PHP variables.

For example, using Angular's $http post example:

$http.post('/someUrl',{var1: 'here', var2: 'here'}).success(successCallback);

You would have to use the following in PHP to read the var1 and var2 parameters

$data = json_decode(file_get_contents("php://input"),false);
$var1 = $data['var1'];
$var2 = $data['var2'];

If you have existing code, you probably don't want to go around refactoring all of your $_POST references. But no worries, there is a way you can configure the $http service to encode it's post data in a way that PHP can understand out of the box. Here is the code:

angular.module("myApp").config(function($httpProvider) {  
       $httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
});

Replace myApp with the name of your Angular's application module. After that, you should be able to access var1 & var2 by simply using $POST['var1'] and $POST['var2'].

Give it a try and let me know if it works for you!