0

Hello i am getting undefined when reading a json file using ajax file. It returns undefined:

var input;
$.getJSON('cake.json', function(data) {
        input = data;
    });
console.log('Result'+input);

but the variable input returns undefined.

1 Answers1

0

You have this:

var input = [];

$.getJSON('cake.json', function(data) {
    input = data;
});

// This will likely execute BEFORE getJSON has returned 'data'
console.log('Result' + input);

But try this and, assuming you're actually getting data, you should see results in the console.

var input = [];

$.getJSON('cake.json', function(data) {
    input = data;
    console.log('Result' + input);
});

(Another way to debug to make sure your JSON call is working is to use the network debugger.)

If you don't need input to be in the global scope (see here about scope of variables in JavaScript), you can just do this:

$.getJSON('cake.json', function(data) {
    // do something with the 'data'
});

or:

$.getJSON('cake.json', function(data) {
    process(data);
});

function process(data) {
    // do something with data
}
Community
  • 1
  • 1
tptcat
  • 3,894
  • 2
  • 32
  • 51