skip to Main Content

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


  1. 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 the Content-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.

    Login or Signup to reply.
  2. JSON.parse can only parse string elements. One solution is to stringify your JSON first:

    JSON.parse(JSON.stringify({"id":"4","username":"muzikant346","coins":"675","avatar1":"1","avatar2":"0","avatar3":"0","avatar4":"0","avatar_selected":"0"}));
    
    Login or Signup to reply.
  3. Another way to fix that first BOM character,

    function stripBOM(content) {
      content = content.toString()
      if (content.charCodeAt(0) === 0xFEFF) {
        content = content.slice(1)
      }
      return content
    }
    
    console.log(JSON.parse(stripBOM(obj)));

    Ref. https://gist.github.com/pbakondy/f5045eff725193dad9c7

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search