"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 Angular HTTP POST values undefined in PHP, and how can I fix it?

Why are my Angular HTTP POST values undefined in PHP, and how can I fix it?

Published on 2024-12-23
Browse:282

Why are my Angular HTTP POST values undefined in PHP, and how can I fix it?

Angular HTTP POST to PHP: Dealing with Undefined POST Values

In AngularJS, performing HTTP POST requests to PHP endpoints can sometimes result in undefined POST values on the server side. This can occur when there is a mismatch between the expected data format and the actual data sent by the Angular application.

To resolve this issue, it's crucial to ensure that the Content-Type header is set appropriately. By default, AngularJS sets this header to "application/json". However, if you're sending form-encoded data, this needs to be overridden.

In the provided code, the following line sets the Content-Type header to "application/x-www-form-urlencoded; charset=UTF-8":

$http.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8';

However, this requires modifying the data sent to match the form-encoded format. Instead of sending the data as an object, it needs to be converted to a query string. This can be done by using jQuery.serialize() or manually building the query string with encodeURIComponent().

Alternatively, if you prefer to use PHP's $_POST functionality, you can keep the default header setting and modify the PHP code to read the raw input from the request body and decode the JSON. This can be achieved with the following code:

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

By aligning the data format and header settings, you can ensure that the POST values are correctly received on the PHP side.

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