4

I want to connect my angular2 app to my PHP backend. Ideally I want to do this:

this.http.post('/users/create', {email: email, password: password});

The problem is, when I do this my $_POST is empty in PHP. What must I do to make this work?

DannySwekker
  • 41
  • 1
  • 2
  • Well explained here: http://stackoverflow.com/questions/36897266/fetch-and-insert-data-into-mysql-using-angularjs – Sanoj Sharma Dec 15 '16 at 12:04
  • That can't be the only solution right? Reading from php://input? I mean with jQuery for example it works with `$_POST` and `json` objects – DannySwekker Dec 15 '16 at 12:18
  • @DannySwekker — jQuery doesn't format the request as JSON by default. It uses the application/x-www-form-urlencoded encoding. You should also [clear up your apparent misconceptions about what JSON is](http://benalman.com/news/2010/03/theres-no-such-thing-as-a-json/). – Quentin Dec 15 '16 at 12:46

2 Answers2

1

Angular's http implementation sends data as an application/json payload. to read such data from php, you have to use this kind of code :

$data = json_decode(file_get_contents("php://input"));
// you can even override the `$_POST` superglobal if you want :
$_POST = json_decode(file_get_contents("php://input"));

if you want to send your data as application/x-www-form-urlencoded and then be able to read it from php's $_POST superglobal without any change to your server code, you need to encode your data as such.

const body = new URLSearchParams();
Object.keys(value).forEach(key => {
  body.set(key, value[key]);
}

let headers = new Headers();
headers.append('Content-Type','application/x-www-form-urlencoded');
this._http.post(this._contactUrl, body.toString(), {headers}).subscribe(res => console.log(res));

I mean with jQuery for example it works with $_POST and json objects

it does not work with json object, if you can read data via $_POST, it means it has been sent as application/x-www-form-urlencoded, not application/json, parameters are set as a plain js object though...

n00dl3
  • 21,213
  • 7
  • 66
  • 76
  • Is there any way to have this done by every request? I'm quite confused that it's such a hassle, when I feel that every php application should have this problem right? If they want to work with angularjs – DannySwekker Dec 15 '16 at 14:53
  • just create a custom service that will wrap `http` calls. I don't think it's quite a problem because mot people use JSON API to comunicate with the server. – n00dl3 Dec 15 '16 at 15:23
0

you can use php://input for the post data with angular2 like this and json_decode by this

$arr = json_decode(file_get_contents('php://input'),TRUE);
echo "<pre>";print_r($arr);exit;

so by this $arr prints the whole post array and used it anywhere you want.

Darshan ambaliya
  • 301
  • 3
  • 20