I am using angular 2, and I am trying to send data from angular through a post request to a php file on my server. When I try, I get this error "SyntaxError: Unexpected token < in JSON at position 0". Here is the code I have so far. Any assistance would be appreciated. Thanks!
App component button
<button class="btn btn-primary btn-lg" (click)="postData()"> Make Post Request </button>
app component code I use this function and call it on a button in the template to send the request
postData(){
this.requestService.postSomeData()
.subscribe(
data => this.postRequest = data,
error => console.log('There is an error: ' + error),
() => console.log("Completed Post Request!")
);
}
Request Service code -- Here is the service I am calling in the app component
postSomeData(){
let url = 'link to php file here';
let jsonData = {
name: 'my Name'
};
let headers = new Headers();
headers.append('Content-Type', 'application/x-www-form-urlencoded');
return this.http.post(url, jsonData, {headers: headers})
.map(res => res.json());
}
PHP File
<?php
$postdata = file_get_contents("php://input");
$request = json_decode($postdata);
$name = $request->name;
echo "Name: ".$name;
?>
The problem come from the fact that in the PHP (server-side I assume) there is no response returned.