1

I want to get the data from the JSON file, it works fine on my computer, but when I put it on my server, it shows this error.

Error: Uncaught SyntaxError: expected expression, got '<'

This is my code:

setInterval(function () {
    loadJSON(function (response) {
        jsonresponse = JSON.parse(response);
        document.getElementById('stats').innerHTML = jsonresponse[0].name;
    });
}, 1000);

function loadJSON(callback) {
    var xobj = new XMLHttpRequest();
    xobj.overrideMimeType('application/json');
    xobj.open('GET', 'data.json', true);
    xobj.onreadystatechange = function () {
        if (xobj.readyState == 4 && xobj.status == '200') {
            callback(xobj.responseText);
        }
    }
    xobj.send(null);
}
<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Document</title>
        <link rel="stylesheet" href="/style.css">
    </head>
    <script src="./index.js"></script>
    <script src="./node.js"></script>
    <script src="./data.json"></script>
    </body>
</html>

Any idea of how to fix this?

K.K Designs
  • 688
  • 1
  • 6
  • 22
Velix
  • 49
  • 1
  • 5
  • 2
    You'll need to check what the server is returning to your browser. You can do that with the "Network" tab in the browser developer tools. – Pointy Feb 09 '22 at 20:08
  • 1
    Your `XMLHttpRequest` statement seems to be returning either `HTML` or `XML` response. Also, switch to the `Fetch API`; it's a lot better and easier to use. – K.K Designs Feb 09 '22 at 20:13
  • I just tried the thing with the "Network" tab and found out that the Index.js is detected as a html file, so when I go to "http://82.165.168.16/index.js" (you can try it) it shows my index.html.. anyone know's why? – Velix Feb 09 '22 at 20:31
  • @Velix Can you approve my edit? – K.K Designs Feb 09 '22 at 20:47
  • @Velix Well that means that your http server is not working, or the "*I put it on my server*" didn't succeed. Nothing in the code you posted causes this error. If you need help with why your server serves the wrong file when requesting *index.js*, you'll need to show us its code and/or configuration. – Bergi Feb 09 '22 at 21:05

2 Answers2

2

Well I fixed it by just deleting and recreating the file. Thanks for your help I appreciate it!

Velix
  • 49
  • 1
  • 5
0

Why have you added json file in script tag <script src="./data.json"></script>

Also are the files available on your server? Sometimes this error happens when the Javascript referenced file doesn't exist.

Prim
  • 1,312
  • 5
  • 25
  • 51
  • Yes the files exist and I heard that you have to do that. – Velix Feb 09 '22 at 20:26
  • The – Prim Feb 09 '22 at 20:29
  • https://stackoverflow.com/questions/12070631/how-to-use-json-file-in-html-code scroll a bit down – Velix Feb 09 '22 at 20:38