How to do $http POST with AngularJS in php

Doing a POST request in AngularJS is bit tricky. If you do it like below, you cannot access the POST variables with $_POST or $_REQUEST via php. With the below method, you can access POST variables only via file_get_contents();

How to get POST values with above method

The reason is, AngularJS doesn’t serialize the data ( parameters ) passed to the POST request automatically. Therefore we have to serialize the data with $.params() which is available in jQuery . Also the default content-type of the posted data is application/json. Therefore we need to override the Content-type headers of the post request to application/x-www-form-urlencoded in order to access the the posted values via $_POST or $_REQUEST

You can access POST values in above method as shown below.

10 thoughts on “How to do $http POST with AngularJS in php

  1. Tjorriemorrie

    Yeah, this is AWESOME!!! I’ve been struggling for ever to find something that works elegantly. Will it work with file uploads as well?

  2. Thomas Kingo

    This article totally saved my day!
    I added the $.param and the header “content-type” in the module.config().
    Now I can pass data with the regular $http shorthand and receive it in php with $_POST.
    Thanks for sharing. Much appreciated!

  3. Wolf PayDay

    Thank you so much!!! I’ve been struggling for 3 days to find out a well explained solution for me!! Thank you so much again!!! FANTASTIC!


Leave a Reply

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