Home > database >  Getting an UNDEFINED on a JSON call
Getting an UNDEFINED on a JSON call

Time:11-27

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.

CodePudding user response:

you should remove brackets from user.json file.

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