0

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);
}
  1. Why do I have to specify the name of the json I'm passing? I mean the newUser prefix under the data of the request.
  2. Secondly, why do I have to json.parse twice the response in order to convert it back to a JS Object?
  3. Why to I have to specify the headers in order to pass a simple JSON string?
cn007b
  • 16,596
  • 7
  • 59
  • 74
Alex
  • 1,982
  • 4
  • 37
  • 70
  • Simply to serialize the data – saravanabawa Dec 03 '16 at 12:44
  • If you send back json data add the appropriate headers `header('Content-Type: application/json');` this can help other's library to automatically convert it to json – Endless Dec 03 '16 at 12:48
  • This could help you: http://stackoverflow.com/questions/18866571/receive-json-post-with-php (then you don't have to serialize the data) you could just send json – Endless Dec 03 '16 at 12:52
  • 1
    see here for the correct answer: http://stackoverflow.com/a/15485690/2401804. just put a raw object as the `data` argument in your post request in the angular code. KISS = Keep It Simple Stupid. – r3wt Dec 03 '16 at 13:52
  • Possible duplicate of [Angular HTTP post to PHP and undefined](http://stackoverflow.com/questions/15485354/angular-http-post-to-php-and-undefined) – r3wt Dec 03 '16 at 13:52

1 Answers1

0

Q1. Why do I have to specify the name of the json I'm passing? I mean the newUser prefix under the data of the request.

Q3. Why to I have to specify the headers in order to pass a simple JSON string?

In PHP, you have global arrays like $_POST & $_GET to receive the data extracted from the request that are on the form of key=value. And $_POST is filled when using application/x-www-form-urlencoded or multipart/form-data as the HTTP Content-Type.

So in order to use these global arrays, you have to full-fill these two conditions

Okay the alternative way is to use php://input stream to directly read the raw input, so you can send the json string directly.

file_get_contents(“php://input”);
Shady Atef
  • 2,121
  • 1
  • 22
  • 40