1

So I'm creating a simple Web Page that takes data from a json file and appends a number of paragraphs equal to the number of objects in the json file array:

$(function () {

    function init() {
       console.log("OK");
       var dat;
       var i;
       load();
       fill();
   }

   function load()
   {
       $.get("data.json", function (data, status) {
           dat=data;
           console.log(dat);
       })
   }

   function fill()
   {
       console.log(dat);
       for(i=0; i<dat.length(); i++) $("#container").append("<p>Testing</p> <br/><br/>")
   }

    $(".front").on("load", init());
});

However when I run the web page the first time I try to do a console log it prints out the data however the second time, inside the fill() function it says:

"Uncaught ReferenceError: dat is not defined"

Any ideas?

Stephen Docy
  • 4,738
  • 7
  • 18
  • 31
David Mathers
  • 163
  • 2
  • 7

2 Answers2

4

There are several problems:

  1. dat is a local variable within your init function, so naturally code in your load function doesn't have access to it.

  2. You're calling init and then passing its return value into on, not hooking up init as a load handler.

  3. $.get is asynchronous, so just calling load and then calling fill won't work, fill will run before the GET has completed.

See comments:

$(function () {
   var dat; // *** Make this global to the code (it's not actually global, which is good)

   function init() {
       load(fill); // *** Pass `fill` into `load`
   }

   function load(next) // *** Accept the callback to call when ready
   {
       $.get("data.json", function (data, status) {
           dat = data;
           console.log(dat);
           next(); // *** Call it
       })
   }

   function fill()
   {
       console.log(dat);
       for(i=0; i<dat.length(); i++) $("#container").append("<p>Testing</p> <br/><br/>")
   }

    $(".front").on("load", init); // *** No () on init, you want to pass the function into `on`, not *call* the function
});

Some other notes:

  1. You might also look into promises.

  2. Unless you need dat for more than fill, consider not having the dat variable at all; just have load call fill with the data as an argument.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
0

Variable dat is in scope of function init() and it doesnt exists outside that function , move variable dat outside function.

var dat;

function init(){

// rest of code

}

Mirko Acimovic
  • 508
  • 2
  • 9