8

I try to post data from angular 2 to php:

let headers = new Headers();
headers.append('Content-Type', 'application/json');
var order = {'order': this.orders};

this.http.post('http://myserver/processorder.php', JSON.stringify(order), {
    headers: headers
}).subscribe(res => {
    console.log('post result %o', res);
});

In angular 2 one can only post string as data and not Json? That's ok for me but I struggle to get the posted data on php. I tried $obj = $_POST['order'];

John Slegers
  • 41,615
  • 22
  • 193
  • 161
daniel
  • 32,027
  • 36
  • 92
  • 151
  • 1
    PHP expects post data to be in `key=value` pairs when it's building $_POSt. you didn't sent that, you sent a raw json string, which is basically just the `value` component. since there's no `key`, php can't put anything into `$_POST`, because an array item must have a key. you could probably retrieve the json by reading from `php://input`. – Marc B Feb 10 '16 at 21:07

3 Answers3

8

Marc B is correct, however what is happening is that the $_POST array will contain an empty value with a key set to the JSON string you are passing...

Array
(
    [{"order":"foobar"}] => 
)

You "can" grab that (although this would be the wrong approach) by getting the key using...

key($_POST)

for example:

$obj = json_decode(key($_POST));
echo $obj->order;

BUT what you can do is send the data as value key pairs:

let headers = new Headers();
headers.append('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
let order = 'order=foobar';

this.http.post('http://myserver/processorder.php', order, {
    headers: headers
}).subscribe(res => {
    console.log('post result %o', res);
});

Then in PHP you can grab the data using:

$_POST['order']

Few things to note:

  • changed header Content-Type to application/x-www-form-urlencoded (more for my own testing since this doesn't do any preflight requests)
  • notice that order is a key value pair string instead of JSON
  • notice that order in this.http.post is getting passed as-is without JSON.stringify
inki
  • 1,907
  • 19
  • 24
4

I do not know if it's bad practice but it seems right to me, although it bothers me a little

const headers = new Headers();
headers.append('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');

const obj = { nome: 'gabriel', age: 20 };
const body = 'data=' + JSON.stringify(obj);

this.http.post('/test.php', body, { headers })
  .subscribe(res => console.log(res.json()), res => console.error(res))

And in php

$post = json_decode($_POST['data']);
Gabriel Martins
  • 468
  • 3
  • 9
2

Agreed with you that we can't at the moment provide object instead of string. It's a feature in progress. See this issue:

Regarding your problem to get JSON data on the server side, this question should help you:

Community
  • 1
  • 1
Thierry Templier
  • 191,422
  • 38
  • 386
  • 349