Home > Web Front-end > JS Tutorial > Why Are My AngularJS POST Variables Undefined in My PHP Script?

Why Are My AngularJS POST Variables Undefined in My PHP Script?

Susan Sarandon
Release: 2024-11-30 12:43:11
Original
132 people have browsed it

Why Are My AngularJS POST Variables Undefined in My PHP Script?

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;
Copy after login

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'];
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template