Home >Web Front-end >JS Tutorial >Why are my AngularJS HTTP POST variables undefined in my PHP script?

Why are my AngularJS HTTP POST variables undefined in my PHP script?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-02 04:43:13729browse

Why are my AngularJS HTTP POST variables undefined in my PHP script?

AngularJS HTTP Post to PHP: Addressing Undefined Variables

Your AngularJS code is experiencing an issue where data posted to a PHP script is appearing undefined. To resolve this, we need to delve into the details.

In your AngularJS code, you have defined an HTTP POST request with a Content-Type header of "application/x-www-form-urlencoded". However, your data is not formatted as a query string. PHP relies on $_POST to receive form-encoded data, which requires the data to be formatted as key-value pairs.

To fix this issue, there are two options:

Option 1: Use JSON

AngularJS defaults to using the "application/json" Content-Type header for HTTP requests. You can leverage this by reading the raw input in PHP and deserializing the JSON. This can be done using the following PHP code:

$postdata = file_get_contents("php://input");
$request = json_decode($postdata);
$email = $request->email;
$pass = $request->password;

Option 2: Manually Format Query String

If you prefer using $_POST, you can manually format your data as a query string. Ensure it is URL encoded. In JavaScript, you can achieve this using:

let data = "email=" + encodeURIComponent($scope.email) + "&password=" + encodeURIComponent($scope.password);

Set the HTTP request data to this formatted query string instead of the current format. With these adjustments, your AngularJS HTTP POST request will correctly send data to your PHP script, resolving the issue of undefined variables.

The above is the detailed content of Why are my AngularJS HTTP POST variables undefined in my PHP script?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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