I'm studying php
and angular
. Currently exploring the possibilities to send data to server side using $http
service. This is what I came up with and it seem to work, but it doesn't look elegant.
Angular code:
$http({
method: 'POST',
url: 'server.php',
data: "newUser=" + JSON.stringify(user),
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
} // set the headers so angular passing info as form data (not request payload)
})
.success(function (respose) {
var x = JSON.parse(respose);
console.log(JSON.parse(x));
}).error(function (err) {
console.log(err);
console.log("some kind of error");
});
This is my php
code to receive the data and return it:
if (isset($_POST["newUser"])) {
$newUser = $_POST["newUser"];
echo json_encode($newUser);
}
- Why do I have to specify the name of the
json
I'm passing? I mean thenewUser
prefix under thedata
of the request. - Secondly, why do I have to
json.parse
twice the response in order to convert it back to a JS Object? - Why to I have to specify the headers in order to pass a simple JSON string?