Problem Description:
When performing an HTTP POST request from AngularJS to a PHP script, the PHP script receives undefined values for the posted form data.
Cause:
AngularJS defaults the Content-Type header for HTTP Post requests to application/json. However, the sample code in the question sets the Content-Type header to application/x-www-form-urlencoded. As a result, the data sent by AngularJS is not in the expected format for PHP's $_POST functionality.
Solution 1:
Use the default AngularJS Content-Type header of application/json and read the raw input in PHP, then deserialize the JSON.
$postdata = file_get_contents("php://input"); $request = json_decode($postdata); $email = $request->email; $pass = $request->password;
Solution 2:
If relying on $_POST functionality, form a query string from the data and send it as the request body, ensuring that the query string is URL encoded.
data = "email=" + encodeURIComponent($scope.email) + "&password=" + encodeURIComponent($scope.password);
The above is the detailed content of AngularJS to PHP POST: Why are my variables undefined?. For more information, please follow other related articles on the PHP Chinese website!