0

I'm using ajax and jQuery to load a json content but when I print it, I got nothing.

index.php

<!DOCTYPE html>
<html>
<head>
</head>
<body>
    <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
    <script>
        (function($){
        $.ajax({
            type: 'GET',
            dataType: 'json',
            url: 'content.json',
            success: function(data) {
                response = $.parseJSON(data);
                console.log(data);
                console.log(response);
            }
        });
    })(jQuery);
    </script>
</body>
</html>

content.json:

[
  {
    "name": "Meowsy",
    "species" : "cat",
    "foods": {
      "likes": ["tuna", "catnip"],
      "dislikes": ["ham", "zucchini"]
    }
  },
  {
    "name": "Barky",
    "species" : "dog",
    "foods": {
      "likes": ["bones", "carrots"],
      "dislikes": ["tuna"]
    }
  },
  {
    "name": "Purrpaws",
    "species" : "cat",
    "foods": {
      "likes": ["mice"],
      "dislikes": ["cookies"]
    }
  }
]

Why I don't get anything in the console?

If I want to print for example sony/id(1)/game... what would be the right code, please?

Kokos98
  • 1
  • 1
  • Any errors? My assumption would be you're getting a parse error around something at character "o" – Taplar Apr 16 '19 at 16:40
  • That `content.js` doesn't look like valid JavaScript or JSON. It looks like PHP - are you sure it's interpreted before the file is handed over to the browser? And what's the content of `data` – VLAZ Apr 16 '19 at 16:41
  • Please try without `dataType: 'json',` – Wang Liang Apr 16 '19 at 16:41
  • Oh, good catch. Yeah the json is invalid, so jQuery trying to auto parse it due to the dataType is going to fail and call the error callback. There should definitely be errors in the console. – Taplar Apr 16 '19 at 16:42
  • I have edited the code, I took a valid json file and used it instead, plus Im using json format now, not js. Lastly Im printing data and response... but I got the same problem. :( getting: `Uncaught SyntaxError: Unexpected token o in JSON at position 1` – Kokos98 Apr 16 '19 at 17:33
  • Log the content of `data` *before* you do `parseJSON`. You're very likely already getting the parsed result back, hence why when you parse it again you will get an error - calling `parseJSON` on an object will turn the object into a primitive which is the value `"[object Object]"` and hence the parsing fails at the second character because it's not valid JSON. – VLAZ Apr 16 '19 at 17:58
  • @VLAZ that was it , thank you very much. – Kokos98 Apr 16 '19 at 23:25

0 Answers0