Peter Wilson Peter Wilson - 6 months ago 179
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

$http({
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) {
["interpreterDetails"]=>
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"}"
["serviceID"]=>
string(4) "0001"
}


but the expected return is

object(stdClass)#3 (8) {
["serviceID"]=>
string(4) "0001"
["interpreterDetails"]=>
object(stdClass)#4 (13) {
["firstName"]=>
string(5) "zxczc"
["lastName"]=>
string(4) "zxcz"
["password"]=>
string(4) "1234"
["rePassword"]=>
string(4) "1234"
["address"]=>
string(4) "sada"
["mobPhone"]=>
string(4) "4532"
["homePhone"]=>
string(4) "1351"
["mail"]=>
string(11) "asd@sdsd.sd"
["fax"]=>
string(6) "123513"
["hourlyRate"]=>
string(2) "26"
["OperatingSys"]=>
string(0) ""
["token"]=>
string(0) ""
["dialectId"]=>
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

Answer

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