AngularJS HTTP post to PHP and undefined
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);
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.