Monthly Archives: April 2016

AngularJS2: Send HTTP Post request with parameters to PHP

After some troubles trying to reach an old PHP server (Using $_POST to retrieve parameters) with a new Ionic2 project (so using AngularJS2 Http).
Here is what worked :

var headers = new Headers();
headers.append('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
 
var params = 'email=email@example.com&pwd=xxxxxx';
 
this.http.post('http://mysite.com/api', params , {headers: headers})
  .subscribe(
    data => console.log('Received:' + data),
    err => console.log(err),
    () => console.log('Call Complete')
  );

The important parts are :

  • The Content-Type (By default: plain/text which won’t work on PHP server side) set to application/x-www-form-urlencoded
  • Parameters should be passed as a Query String
  • Don’t forget the imports (Forgetting Headers won’t crash but you’ll send plain/text)
    import {Http, Headers} from 'angular2/http';