I'm getting the following error when trying to make an ajax request (with Angularjs) to my PHP API.
SyntaxError: Unexpected token n in JSON at position 24
I'd appreciate any help. Thanks
Here is my Angular JS code:
var data = {"username":"sarahexample", "password":"5f4dcc3b5aa765d61d8327deb882cf99"};
$http({
method: 'POST',
url: 'http://localhost/API/auth',
data : JSON.stringify(data)
}).then(function successCallback(response) {
console.log(response);
}, function errorCallback(response) {
console.log(response);
});
And here is the PHP auth function which executes when that endpoint is requested.
protected function auth($parameters) {
if ($this->method == 'POST') {
//echo the POST data back to the client side to test it's working
//This works when I take out the php Content-Type header
echo json_encode($_POST);
} else {
//echo "Only accepts POST requests";
}
}
In my PHP API I have the following header (which when taken out everything works fine however I'd like it to work with the header).
header("Content-Type: application/json");
I tried leaving in the above header and also adding in contentType: 'application/json'
in the ajax request as follows (however this did not solve the JSON error):
$http({
method: 'POST',
url: 'http://localhost/API/auth',
contentType: 'application/json',
data : JSON.stringify(data)
}).then(function successCallback(response) {
console.log(response);
}, function errorCallback(response) {
console.log(response);
});
In the Network tab in the console:
Request URL:http://localhost/API/auth
Request Method:POST
Status Code:200 OK
Remote Address:[::1]:80
Referrer Policy:no-referrer-when-downgrade
Response Headers
view source
Access-Control-Allow-Methods:*
Access-Control-Allow-Origin:*
Connection:Keep-Alive
Content-Length:6
Content-Type:application/json
Date:Thu, 28 Sep 2017 17:17:31 GMT
Keep-Alive:timeout=5, max=100
Server:Apache/2.4.27 (Win64) PHP/5.6.31
X-Powered-By:PHP/5.6.31
Request Headers
view source
Accept:application/json, text/plain, */*
Accept-Encoding:gzip, deflate, br
Accept-Language:en-US,en;q=0.8
Cache-Control:no-cache
Connection:keep-alive
Content-Length:73
Content-Type:application/json
Host:localhost
Origin:http://localhost
Pragma:no-cache
Referer:http://localhost/phonegap_tut/
Request Payload
view source
{username: "sarahexample", password: "5f4dcc3b5aa765d61d8327deb882cf99"}
password
:
"5f4dcc3b5aa765d61d8327deb882cf99"
username
:
"sarahexample"