0

I'm trying to make a post request with Angular 4 with this code to send lat and lng parameters:

let data = {lat: this.newLat, lng: this.newLng};

this.http.post(url, data)
  .map(response => response.json())
  .subscribe(getResponse => console.log(getResponse));

On the server side, I have the following php snippet:

header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: Content-Type");

if ( isset($_POST['lat'], $_POST['lng']) ) {
    $response['msg'] = 'ok';
} else {
    $response['msg'] = 'not ok';
}
echo json_encode($response);

The response from the server is unfortunately always 'not ok'. Any ideas how to solve this? The $_POST variable is always an empty array

Piotr Pliszko
  • 676
  • 5
  • 9
Bernardo Peters
  • 163
  • 2
  • 9

2 Answers2

0

See the documentation

If the data property of the request configuration object contains an object, serialize it into JSON format.

and

$httpProvider.defaults.headers.post: (header defaults for POST requests) Content-Type: application/json


Angular is encoding the data as JSON, and not one of the data formats which PHP will automatically parse into $_POST.

You need to parse JSON as described in this answer.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
0

The PHP superglobal $_POST, only is supposed to wrap data that is either, application/x-www-form-urlencoded or multipart/form-data-encoded.

But if the Content-Type for request is anything else. You need to use:

$post = file_get_contents('php://input');

For more info look at this answer: https://stackoverflow.com/a/8893792/2394254

mega6382
  • 9,211
  • 17
  • 48
  • 69