0

During a [ajax/json tutorial], I only had one error. I followed the tutorial through and through, but where outputting the object value for "name", I kept getting an 'undefined' for my output. The only way I could get it to output "Rick" was by using console.log(user[0].name) instead of what the tutorial had, "console.log(user.name)". The var user was JSON.parse as instructed.

JSON FILE (user.json):

[
    {
        "id": 1,
        "name": "Rick",
        "email": "[email protected]"
    }
]

HTML File (ajax2.html):

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Ajax 2 - Local JSON</title>
    <style>
        *, html { background: #333; color: #eee; }
    </style>
</head>
<body>
    <button id="button1">Get User</button>
    <button id="button2">Get Users</button>
    <br /><br />
    <h1><div id="user"></div></h1>
    <br />
    <h2><div id="users"></div></h2>

    <script>
        function loadUser() {
            var xhr = new XMLHttpRequest();
            xhr.open('GET', 'user.json', true);

            xhr.onload = function() {
                if(this.status == 200) {
                    var user = JSON.parse(this.responseText);
                    console.log(user.name); // Output name "Rick"
                }
            }

            xhr.send();
        }

        document.getElementById('button1').addEventListener('click', loadUser);


    </script>

</body>
</html>

I keep getting an Undefined. But coding:

if(this.status == 200) {
    console.log(this.responseText); // Output the object key/values
}

Would output the object properly.

Any ideas as to why I would be getting an undefined? I'm using XAMPP and my Chrome browser is up-to-date as well.

Let me know if I need to add any information. I've searched for possible answers, but it just led me into a rabbit hole.

2
  • 2
    "instead of what the tutorial had" - your tutorial is wrong then. user is an array.
    – Spectric
    Commented Nov 26, 2021 at 18:07
  • My mistake. I meant array, not object. Nonetheless, my question is still why did it work on on the video tutorial and not for me. I appreciate you explaining the difference as well.
    – Lexiriam
    Commented Nov 26, 2021 at 18:18

1 Answer 1

1

you should remove brackets from user.json file.

{
    "id": 1,
    "name": "Rick",
    "email": "[email protected]"
}
1
  • THANK YOU! That was it. I overlooked the brackets on the user.json file. My eyes were criss-crossed from jumping into the rabbit hole of trying to research it myself.
    – Lexiriam
    Commented Nov 26, 2021 at 18:20

Not the answer you're looking for? Browse other questions tagged or ask your own question.