AngularJS2: Send HTTP Post request with parameters to PHP

By | April 17, 2016

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';

2 thoughts on “AngularJS2: Send HTTP Post request with parameters to PHP

  1. JohnP

    Hi Michael,

    When we make http request and error occured, then finally callback is never fired. Is this expected behaviour?

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *