Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS HTTP post to PHP and undefined

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

The function gets called fine in javascript.

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

    $scope.email    = "[email protected]";
    $scope.password = "1234";

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

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

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

<?php
$email = $_POST['email'];
$pass  = $_POST['password'];
echo $email;
?>

Any idea why I am getting undefined POST values?

EDIT

I wanted to point out since this seems to be a popular question (yet it is old), .success and .error have been deprecated and you should use .then as @James Gentes pointed out in the commments

like image 856
Ronnie Avatar asked Mar 18 '13 19:03

Ronnie


3 Answers

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 [email protected]&password=somepassword 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.

like image 170
Mike Brant Avatar answered Nov 11 '22 11:11

Mike Brant


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);
like image 41
valmarv Avatar answered Nov 11 '22 10:11

valmarv


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.

like image 15
Tim Wickstrom Avatar answered Nov 11 '22 10:11

Tim Wickstrom