-3

I have the json file result.json looking as follows:

{
"employees":[
    {"firstName":"John","lastName":"Doe" },
    {"firstName":"Anna","lastName":"Smith" },
    {"firstName":"Peter","lastName":"Jones" }]
}

In my html file I'm trying to use jQuery to access one of the objects from the json file, i.e. one of the persons, and display some of the objects data.

<!DOCTYPE html>
<html>
<body>
<head>
    <script type = "text/javascript" src = "http://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
</head>

<p id="demo"></p>

<script>
    var obj;
    $.getJSON("http://insyn.local:666/result.json", function(json){
        obj = json;
    });
    document.getElementById("demo").innerHTML =
    obj.employees[1].firstName + " " + obj.employees[1].lastName;
</script>

</body>
</html>

But this only gives me the error "Uncaught TypeError: Cannot read property 'employees' of undefined". What am I missing here?

Craicerjack
  • 6,203
  • 2
  • 31
  • 39
Agent Shoulder
  • 586
  • 8
  • 22
  • 1
    Due to the asynchronous nature of JS, you need to put the `innerHTML` statement in the callback function of the `getJSON` call. Otherwise, the innerHTML will run before the results are returned. – helllomatt Apr 18 '16 at 14:16
  • 1
    `$.getJSON` is an asynchronous call and probably hasnt completed when you try to insert it into the DOM – Craicerjack Apr 18 '16 at 14:16

1 Answers1

0

Try doing your html manipulation inside the callback:

<!DOCTYPE html>
<html>
<body>
<head>
    <script type = "text/javascript" src = "http://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
</head>

<p id="demo"></p>

<script>
    var obj;
    $.getJSON("http://insyn.local:666/result.json", function(json){
        obj = json;
        document.getElementById("demo").innerHTML =
        obj.employees[1].firstName + " " + obj.employees[1].lastName;
    });

</script>

</body>
</html>
Paul
  • 35,689
  • 11
  • 93
  • 122