1

I want to access data from a JSON data file to print this to a HTML page by using a javascript file. So far it return 'undefined' and I can't work out why. Heres the code in my files:

template.html:

<!DOCTYPE html>
<html>
  <head>
    <script type ="text/javascript" src="populate.js"></script>
  </head>

  <body>
    <script>
      document.write(me);
    </script>
  <body>

this is my stuff.json file:

[
{"firstname":"James", "lastname":"Davies", "Age":"25"},
{"firstname":"Bill", "lastname":"Jones", "Age":"40"}
]

and this is populate.js

var me;
$.getJSON("stuff.json", function(data) {
  me = data;
});

All these files are in the same directory. I dont know why the me variable isn't being inherited by the javascript file and therefore printed to the html page.

trouselife
  • 971
  • 14
  • 36
  • 2
    The problem is because the AJAX request is asynchronous, so you're writing your `me` variable to the DOM before it's been set. It's like trying to eat a pizza before it's been delivered. See the question I marked as duplicate for more information and solutions to the issue. Also, never use `document.write()`. – Rory McCrossan Dec 09 '16 at 13:59
  • Also as you have an array of objects which you're trying to write to the DOM directly it'll just be coerced to a string, so the output will be `[object Object],[object Object]` which I'm guessing isn't what you want. I'd suggest you research how to loop through that array and read the properties of the contained objects. – Rory McCrossan Dec 09 '16 at 14:01
  • Hi, thanks, I cant actually see the question you marked as duplicate? And what should I used instead of document.write()? – trouselife Dec 09 '16 at 14:02
  • It's in the yellow banner at the top. You may need to refresh the page. As for alternatives to `document.write`, literally anything, create a new element/textNode, `appendChild()`, or in jQuery `.html()`, `.text()`, `append()`... – Rory McCrossan Dec 09 '16 at 14:03

1 Answers1

0

Maybe it's a race condition, try:

 window.onload = function() { 
        document.write(me);
    }
Samuil Petrov
  • 542
  • 1
  • 13
  • 24