angular http post to php and undefined

angular http post to php and undefined  using -'php,javascript,angularjs'

I have a form with the tag ng-submit="login()

The function gets called fine in javascript.

function LoginForm($scope, $http)
    $['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8';

    $    = "";
    $scope.password = "1234";

    $scope.login = function()
        data = {
            'email' : $,
            'password' : $scope.password

        $'resources/curl.php', data)
        .success(function(data, status, headers, config)
            console.log(status + ' - ' + data);
        .error(function(data, status, headers, config)

I am getting a 200 OK response back from the PHP file, however, the returned data is saying that email and password are undefined. This is all the php I have

$email = $_POST['email'];
$pass  = $_POST['password'];
echo $email;

Any idea why I am getting undefined POST values?

asked Sep 22, 2015 by rajesh
0 votes

8 Answers

0 votes

angularjs .post() defaults the Content-type header to application/json. You are overriding this to pass form-encoded data, however you are not changing your data value to pass an appropriate query string, so PHP is not populating $_POST as you expect.

My suggestion would be to just use the default angularjs setting of application/json as header, read the raw input in PHP, and then deserialize the JSON.

That can be achieved in PHP like this:

$postdata = file_get_contents("php://input");
$request = json_decode($postdata);
$email = $request->email;
$pass = $request->password;

Alternately, if you are heavily relying on $_POST functionality, you can form a query string like and send that as data. Make sure that this query string is URL encoded. If manually built (as opposed to using something like jQuery.serialize()), Javascript's encodeURIComponent() should do the trick for you.

answered Sep 22, 2015 by patelnikul321
0 votes

In the API I am developing I have a base controller and inside its __construct() method I have the following:

if(isset($_SERVER["CONTENT_TYPE"]) && strpos($_SERVER["CONTENT_TYPE"], "application/json") !== false) {
    $_POST = array_merge($_POST, (array) json_decode(trim(file_get_contents('php://input')), true));

This allows me to simply reference the json data as $_POST["var"] when needed. Works great.

That way if an authenticated user connects with a library such a jQuery that sends post data with a default of Content-Type: application/x-www-form-urlencoded or Content-Type: application/json the API will respond without error and will make the API a little more developer friendly.

Hope this helps.

answered Sep 22, 2015 by maurya
0 votes

I do it on the server side, at the begining of my init file, works like a charm and you don't have to do anything in angular or existing php code:

if ($_SERVER['REQUEST_METHOD'] == 'POST' && empty($_POST))
    $_POST = json_decode(file_get_contents('php://input'), true);
answered Sep 22, 2015 by sachin valanju
0 votes

Because PHP does not accept JSON 'application/json' you can update your headers and parameters from angular appropriately.

First, Parameterize your data:

data: $.param({ "foo": $scope.fooValue })

Then, add the following to your $http

 headers: {
     'Content-Type' : 'application/x-www-form-urlencoded; charset=UTF-8'

If all of your requests are going to PHP the parameters can be set globaly in the configuration as follows:

myApp.config(function($httpProvider) {
    $['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8';
answered Sep 22, 2015 by abhimca2006
0 votes

Angular Js Demo Code :-

angular.module('ModuleName',[]).controller('main', ['$http', function($http){

                var formData = { password: 'test pwd', email : 'test email' };
                var postData = 'myData='+JSON.stringify(formData);
                        method : 'POST',
                        url : 'resources/curl.php',
                        data: postData,
                        headers : {'Content-Type': 'application/x-www-form-urlencoded'}  



Server Side Code :-

Due to angular behaviour there is no direct method for normal post behaviour at PHP server, so you have to manage it in json objects.

answered Sep 22, 2015 by shikhar jain
0 votes

You need to deserialize your form data before passing it as the second parameter to .post (). You can achieve this using jQuery's $.param (data) method. Then you will be able to on server side to reference it like $.POST ['email'];

answered Sep 22, 2015 by mca.agarwal
0 votes

It's an old question but it worth to mention that in Angular 1.4 $httpParamSerializer is added and when using $, if we use $httpParamSerializer(params) to pass the parameters, everything works like a regular post request and no JSON deserializing is needed on server side.$httpParamSerializer

answered Sep 22, 2015 by amit_cmps
0 votes

This is the best solution (IMO) as it requires no jQuery and no JSON decode:

Source: and:


//Replacement of jQuery.param
var serialize = function(obj, prefix) {
  var str = [];
  for(var p in obj) {
    if (obj.hasOwnProperty(p)) {
      var k = prefix ? prefix + "[" + p + "]" : p, v = obj[p];
      str.push(typeof v == "object" ?
        serialize(v, k) :
        encodeURIComponent(k) + "=" + encodeURIComponent(v));
  return str.join("&");

//Your AngularJS application:
var app = angular.module('foo', []);

app.config(function ($httpProvider) {
    // send all requests payload as query string
    $httpProvider.defaults.transformRequest = function(data){
        if (data === undefined) {
            return data;
        return serialize(data);

    // set all post requests content type
    $['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8';


   var data = { id: 'some_id', name : 'some_name' };
        // It works!
   }).error(function() {
        // :(

PHP code:

answered Sep 22, 2015 by kotmus2002