2

I'm trying to call a web service from angular 5 to PHP.

I'm using POST method but I have trouble retrieving data in PHP side.

Send data is shown in payload but it's not retrieved in php side.

Angular service.ts

this.URL = "http://localhost/angular/WEBSERVICE_PHP/test.php";

const headers = new Headers();
headers.append('Content-Type', 'application/json');
let data = 'visitor_id=55';

return this.http
.post(this.URL,JSON.stringify(data),{
    headers: headers
})
.map( Response => console.log(Response) );

PHP PAGE

header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Credentials: true");
header("Access-Control-Allow-Methods: POST, GET");
header('P3P: CP="CAO PSA OUR"'); // Makes IE to support cookies
header('content-type: text/plain');  
header("content-type: application/x-www-form-urlencoded");
header("Access-Control-Allow-Headers: Content-Type, Authorization, X- 
Requested-With");
header("Access-Control-Max-Age: 172800");

if(isset($_POST))
{
    // $post = 'test data';     // This data get sent
    //   return $post;
    echo $post = $_POST['visitor_id'];
    return $post; 
}
12
  • Don't use post, try file_get_contents('php://input') since you are sending JSON Commented Jul 17, 2018 at 13:27
  • Why are you applying JSON.stringify on data? The way data is defined it looks like it should be JSON.parse instead. Commented Jul 17, 2018 at 13:28
  • var_dump($_POST); It does not contain what you think it does. Try let data = {visitor_id: 55}; and .post(this.URL,data,{, and remove the json header instead. It should be able to read the data without having to use json. If you do want to use json, don't forget to decode it in PHP before you try to access anything. Commented Jul 17, 2018 at 13:32
  • 1
    @delboy1978uk - Your method works all fine. But the server side uses S_POST method for all operations. To avoid rewriting whole post requests. Commented Jul 17, 2018 at 14:17
  • 1
    @delboy1978uk - Even though crooked that works Thanks. Please post the answer. Commented Jul 17, 2018 at 14:24

1 Answer 1

5

When "posting" JSON, you won't see $_POST.

Instead do this:

$json = file_get_contents('php://input');
$array = json_decode($json, true);

If it MUST be $_POST, you can assign the $array to $_POST.

The other solution is from the Angular side, instead of sending the JSON string, send a proper post! (I'm not an Angular man, maybe someone can comment and I'll add the code!)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.