Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Getting an UNDEFINED on a JSON call

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": "rick@mail.com"
    }
]

HTML File (ajax2.html):

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

<!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.

>Solution :

you should remove brackets from user.json file.

{
    "id": 1,
    "name": "Rick",
    "email": "rick@mail.com"
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading