Home > Web Front-end > JS Tutorial > AngularJS to PHP POST: Why are my variables undefined?

AngularJS to PHP POST: Why are my variables undefined?

Linda Hamilton
Release: 2024-11-23 20:07:18
Original
745 people have browsed it

AngularJS to PHP POST: Why are my variables undefined?

AngularJS HTTP Post to PHP: Undefined Variable Issue

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

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

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!

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