2013-05-24

AngularJS POST data to PHP

AngularJS POST data to PHP

By default AngularJS sends all data in json. So if you do a POST request to a PHP code then the $_POST superglobal will not be populated.

This can be solved in two ways - on the client side or on the server side.

Server-side solution

On the server you can parse input and then decode data from json:

$data = file_get_contents("php://input");
$postData = json_decode($data);

Client-side solution

On the client side the data can be sent in a way PHP expects it:

$http({
    url:url
    data : $.param(data),
    method : 'POST',
    headers : {'Content-Type':'application/x-www-form-urlencoded; charset=UTF-8'}
}).success(callback);

Here we set the 'Content-Type' header and encode data using jQuery's $.param. This also can be done for all requests as described on stackoverflow.

3 comments:

  1. This is exactly what i'm looking for. Thanks! ^_^

    ReplyDelete
  2. I used Client-side solution it works fine but some dynamically calculating with angularjs not coming to server

    ReplyDelete
  3. It might help to others
    http://www.code-sample.com/2014/09/angularjs-documentation.html

    ReplyDelete