Bolboa Bolboa - 1 month ago 15
AngularJS Question

response from POST request NULL angular/php

I have a relatively simple POST request in angular...

var data = $.param({
clientID: '329272'
});

var config = {
headers : {
'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8;'
}
}
$http.post('./server.php', data, config)
.success(function (data, status, headers, config) {
console.log(status);
console.log(data);
})
.error(function (data, status, header, config) {
console.log("nope");
});


And my php code that receives the data is the following...

$postdata = file_get_contents('php://input');
$request = json_decode($postdata);

header('Content-Type: application/json');
echo json_encode($request);


All I am doing is sending data, then sending it back in the response to check if it worked.

The connection is made, and console prints out a status of
200
, but when I
console.log(data)
, I get a value of
null
. Why am I not able to receive the data?

Answer

$.param() does not encode into json so json_decode($postdata) parse on the server will fail.

http://api.jquery.com/jquery.param/

This function is used internally to convert form element values into a serialized string representation

You can use JSON.stringify to serialize javascript objects into JSON. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify