When I pass json encoded value from PHP to Javascript and just console log it it returns me this:
{"id":"4","username":"muzikant346","coins":"675","avatar1":"1","avatar2":"0","avatar3":"0","avatar4":"0","avatar_selected":"0"}
This is a string and when I want to parse it in Javascript it returns an error:
eUncaught SyntaxError: Unexpected token in JSON at position 0
at JSON.parse (<anonymous>)
at Object.success (welcome.js:11)
at c (jquery-3.4.1.min.js:2)
at Object.fireWith [as resolveWith] (jquery-3.4.1.min.js:2)
at l (jquery-3.4.1.min.js:2)
at XMLHttpRequest.<anonymous> (jquery-3.4.1.min.js:2)
I don’t understand why javascript can’t parse this.
There is my PHP (fetch from database) code:
$sql = "SELECT * FROM serbian_values WHERE username = '$username'";
$result = mysqli_query($link, $sql);
if($result){
while($row = mysqli_fetch_assoc($result)){
$value[] = $row;
}
echo json_encode($value[0]);
}
3
Answers
A
U+FEFF : ZERO WIDTH NO-BREAK SPACE [BOM] {BOM, ZWNBSP}
is not a valid character to start a JSON text with.Somewhere it is getting inserted into the start of the output of the PHP program (or mixed in before parsing in the JS you haven’t shown us, but that is less likely).
Possibly this is used by the wrong
charset
appearing on theContent-Type
header you are outputting from PHP, but the character is probably just lurking in the source code somewhere. It would probably be easiest to find with a hex editor.JSON.parse
can only parsestring
elements. One solution is to stringify your JSON first:Another way to fix that first BOM character,
Ref. https://gist.github.com/pbakondy/f5045eff725193dad9c7