In my javascript I'm getting this error:
Uncaught SyntaxError: Unexpected token P in JSON at position 0, at JSON.parse (), at XMLHttpRequest.req.onreadystatechange
when trying to receive some stuff from a PHP script. I've seen some similar questions but I couldn't find a solution for my case.
My server PHP code:
<?php
header('Content-Type: application/json');
$myObj->name = "John";
$myObj->age = 30;
$myObj->city = "New York";
$myJSON = json_encode($myObj,JSON_UNESCAPED_UNICODE);
echo $myJSON;
?>
My client javascript:
var req = new XMLHttpRequest();
req.onreadystatechange = function () {
if (this.readyState == XMLHttpRequest.DONE && this.status == 200) {
var s = req.responseText;
var users = JSON.parse(s);
console.table(s);
}
}
req.open("GET", "./get_info.php", true);
When I run the PHP file using the browser I get this:
{"name":"John","age":30,"city":"New York"}
which I believe is correct.
Any suggestion?
1 Answer 1
Your code is working fine, you could check if you are getting any warning in php response which cause an error in JSON.parse at client side, meanwhile same error I got while running your script in my system. Getting Response from php -
<br />
<b>Warning</b>: Creating default object from empty value in <b>/opt/lampp/htdocs/tst/get_info.php</b> on line <b>5</b><br />
{"name":"John","age":30,"city":"New York"}
At Client Side :
Uncaught SyntaxError: Unexpected token < in JSON at position 0
at JSON.parse (<anonymous>)
at XMLHttpRequest.req.onreadystatechange
Fixed this issue by disabling the warning in my php code -
error_reporting(E_ERROR | E_PARSE);
$myObj = new stdClass;
at least