"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > Why are my AngularJS $http.post() variables undefined in my PHP script?

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

Posted on 2025-03-24
Browse:460

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 protected]&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'];
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3