HTTP POST Sent from AngularJS Yields Undefined POST Variables in PHP
In our setup, an AngularJS application sends an HTTP POST request to a PHP script, but the PHP script receives undefined values for the 'email' and 'password' POST parameters.
Debugging the Cause
The issue lies in the mismatch between the Content-Type header sent by AngularJS and the data format expected by PHP. AngularJS uses application/json as the default Content-Type header, but the PHP script expects form-encoded data.
Solution 1: Use Application/JSON in PHP
One solution is to change the Content-Type header in AngularJS to application/json and use PHP's file_get_contents("php://input") to retrieve the raw request body. The data can then be deserialized from JSON.
$postdata = file_get_contents("php://input"); $request = json_decode($postdata); $email = $request->email; $pass = $request->password;
Solution 2: Send Form-Encoded Data
Alternatively, AngularJS can be configured to send form-encoded data. This involves building a query string manually or using jQuery.serialize(). The query string should then be URL encoded and set as the request data.
$email = $_POST['email']; $pass = $_POST['password'];
Deprecated Methods
Note that .success() and .error() methods mentioned in the code are deprecated. Use .then() instead.
The above is the detailed content of Why Are My AngularJS POST Variables Undefined in My PHP Script?. For more information, please follow other related articles on the PHP Chinese website!