Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

217
Views
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):

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

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

you should remove brackets from user.json file.

{
    "id": 1,
    "name": "Rick",
    "email": "rick@mail.com"
}
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!