1

I cannot make the following code to work!

<input type="text" ng-model="name" >
<button ng-click="send(name);">SEND</button>

 angular.module('myapp', []).
 controller('MyController', ['$scope','$http', function ($scope,$http) {
    $scope.name='Jim';
    $scope.send=function() {
        return $http({
            method: 'POST',
            data:{server:'Hi'},
            url: 'test.php',
            dataType: 'json'
         }).then(function(data){console.log(data)},function(data){console.log('failure')});
}; 
 }]);

and my very simple test.php:

<?php  
 $request=$_POST['server'];
 $request.='Jim'; 
 echo json_encode($request);
?>

By pressing button SEND, I am getting ($http returns successfully): Object {data: ""Jim"", status: 200, config: Object, statusText: "OK"}. Why data equals that object and why 'Hi' is not passed to PHP? Please, someone to help. I am going to be crazy!

2 Answers 2

3

Probably because in your PHP script you are reading in wrong way the body of the request, try that:

<?php
header("Content-Type: application/json");
$entityBody = file_get_contents('php://input');
$request = json_decode($entityBody);
$request->server .= ' Jim';
echo json_encode($request);
?>
Sign up to request clarification or add additional context in comments.

Comments

1

I just ran into this problem a few days ago. Angular $http doesn't serialize data for POST like php is expecting, and I don't think Content-Type is set correctly either. If you want php to get the request variable $POST as it's expecting and not have to read from 'php://input', you need to serialize your post data and make sure Content-Type is correct. This is what worked for me.

    $http({
    method: 'POST',
    headers: {
        'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8'
        },
    data: formatPostData( {server:'Hi'} ),
    url: 'test.php',
    dataType: 'json'
})

And the funtion used to serialize post data is like this.

function formatPostData( args ) {
    var postString = '';
    angular.forEach( args, function(v, k){
        postString += k + '='+encodeURIComponent(v)+'&';
    })
    return postString.slice(0, -1);
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.