Home > Backend Development > PHP 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?

Linda Hamilton
Release: 2024-12-22 16:22:14
Original
588 people have browsed it

Why are my AngularJS $http.post() variables undefined in my PHP script?

AngularJS: HTTP POST Undefined Variables with PHP

When submitting an AngularJS form using $http.post(), variables received by the PHP script may appear as undefined, despite receiving a 200 OK response.

Causes

By default, AngularJS sets the Content-Type header to application/json for HTTP POST requests. However, if a form-encoded payload is sent instead of JSON data, PHP will not populate the $_POST array as expected.

Solutions

There are two primary solutions:

  1. Use the Default JSON Header:

    • Keep the default Content-Type header of application/json.
    • In PHP, read the raw input and deserialize the JSON data using json_decode().
  2. Send Form-Encoded Data:

    • Set the Content-Type header to application/x-www-form-urlencoded.
    • Manually form a query string such as email=example@email.com&password=secret and send it as the data payload.
    • Make sure to URL-encode the query string using encodeURIComponent().

Example Modified PHP

For the second solution:

$query_string = file_get_contents("php://input");
parse_str($query_string, $data);
$email = $data['email'];
$password = $data['password'];
Copy after login

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!

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