Peter Wilson Peter Wilson - 11 months ago 242
PHP Question

Angular Js $httpParamSerializer and jQuery $.ajax

I am working on an Angular.js app and I have to send a POST request to a PHP server. The data I am sending is object of objects.

Something like:

var data = {
"serviceID": "0001",
"interpreterDetails": {
"firstName": "Peter",
"lastName": "Wilson",
"password": "Peter",
"rePassword": "Peter",
"address": "alex",
"mobPhone": "01224747748",
"homePhone": "3910009",
"mail": "peter@server.domain",
"fax": "556",
"hourlyRate": "10",
"OperatingSys": "android",
"token": "432132",
"dialectId": "1"

when I send this object using angular

url: "http://localhost/saveInterpreter.php",
method: "POST",
data: $httpParamSerializer(data),
headers : {
"Content-Type": "application/x-www-form-urlencoded; charset=UTF-8;"

and the code in the server returns

object(stdClass)#3 (9) {
string(262) " {"firstName":"Peter","lastName":"Wilson","password":"Peter","rePassword":"Peter","address":"alex","mobPhone":"01224747748","homePhone":"3910009","mail":"peter@server.domain","fax":"556","hourlyRate":"10","OperatingSys":"android","token":"432132","dialectId":"1"}"
string(4) "0001"

but the expected return is

object(stdClass)#3 (8) {
string(4) "0001"
object(stdClass)#4 (13) {
string(5) "zxczc"
string(4) "zxcz"
string(4) "1234"
string(4) "1234"
string(4) "sada"
string(4) "4532"
string(4) "1351"
string(11) ""
string(6) "123513"
string(2) "26"
string(0) ""
string(0) ""
string(1) "1"

The problem is that the object inside (interpreterDetails) the outer object (data) is being returned as a string and not an object.

any help with that

NOTE : when I use jQuery it returns the expected results


It would appear that it is being JSON stringified.

You can use json_decode() to to provide expected results

$_POST['interpreterDetails'] = json_decode( $_POST['interpreterDetails'] );

Process would be simpler by using $http default of data sent as application/json and using json_decode(file_get_contents('php://input')) to access the data in php.

EDIT: If you insist on form encoded data try using

data: $httpParamSerializerJQLike(data) 

I've never used it but it may be recursive to replicate the same as jQuery as suggested by it's name