-1

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?

asked Jul 17, 2019 at 0:59
6
  • 5
    Use your browser's "Network" developer tab to inspect the actual response to the HTTP request. Commented Jul 17, 2019 at 1:01
  • In the Network tab the response is "Parameter missing" Commented Jul 17, 2019 at 1:06
  • this should work fine as it stands, it shows a valid json string. there's definitely something fishy on the response or you're not showing the whole php Commented Jul 17, 2019 at 1:10
  • 1
    in case you forgot, initialize the object $myObj = new stdClass; at least Commented Jul 17, 2019 at 1:12
  • 2
    Well that "Unexpected token" is the "P" at the beginning of "Parameter missing". Commented Jul 17, 2019 at 1:13

1 Answer 1

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);
answered Jul 17, 2019 at 1:58

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.