0

Why is it that if I am using Postman, I dont need to include if ($_POST) { '' } else { $_POST = json_decode(file_get_contents('php://input'), true);}

It works differently as If I were to send it from AJAX, but why? Why doesn't Postman requres json_decode(file_get_contents('php://input'), true);

Ajax code

$.ajax({
    url: "http://localhost/WEP/RESTAPI/php.php?api",
    type: "POST",
    data: JSON.stringify(data),
    contentType: "application/json",
    success: function(data) {
      window.alert("Friend added! "+$name.val()+' '+$email.val());
    },
    error: function() { 
        alert("Error");
    } 
});

PHP

elseif ($srequest == 'POST'){

                    if ($_POST) {
                       '';
                    } else {
                        $_POST = json_decode(file_get_contents('php://input'), true);
                    }

                        $id = $_POST['id'];
                        $name = $_POST['name'];
                        $email = $_POST['email'];

                        //...mysqli connect,query
  • try the following javascript ajax call: `$.post( "http://localhost/WEP/RESTAPI/php.php?api", data , function( data ) { window.alert("Friend added! "+$name.val()+' '+$email.val()); }, "json");` . Note that `data` in my example is not stringified. – 500 Server error Feb 13 '17 at 15:27
  • Works the same way as if i didnt change anything – john-thomas Feb 13 '17 at 15:54

2 Answers2

0

Your Ajax has been written to send a POST request with a JSON encoded body.

When you use Postman, you must have configured it to use a multipart or www-url-encoded body.

PHP will automatically decode request bodies using those formats.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
0

Postman does something else then an AJAX post. One will post your classic html form with application/x-www-form-urlencoded, the other is posting straight json with a different contenttype.

bottomline: The php $_POST variable does not containt everyting you send with a POST http request!

also see here, this is an excellent explanation: PHP "php://input" vs $_POST

Community
  • 1
  • 1
Nanne
  • 64,065
  • 16
  • 119
  • 163
  • why is it then, if I set the format the application/json in Postman it doesnt work either, the json format can only be sent from Ajax Post request – john-thomas Feb 13 '17 at 17:11