-1

I have json data in file that I want to read. It prints to the console.log the correct file data.

How do I get that data into variable x? When I run the code, x is undefined.

   function getData() {
        $.get('data/APPFeaturesMetaData.json', function (data) {
            console.log(data);
            return data;
        });
    };

    var x = getData();
Akar
  • 5,075
  • 2
  • 25
  • 39
nanonerd
  • 1,964
  • 6
  • 23
  • 49

1 Answers1

3

It's an asynchronous call, So the var x = getData(); runs before the AJAX request is complete.

The answer is, use deferred it looks something like this:

var request = $.ajax(
{
    url: url,
});

// When the request is done, do something with data.
request.done(function (data) {
    console.log(data);
});

In your case, it's different if you want to return data, you will have some scoping problems. the fix is really easy, Here's what your final code will look like, I will explain stuff in the comments:

function getData() {

    // This is where we store the data.
    var myData;

    // This will refference current object.
    // You need to keep the refference of this object.
    var self = this;

    $.get( 'data/APPFeaturesMetaData.json' ).done(function(data) {
        // the keyword `this` will not work here, because you're inside an AJAX callback.
        // When you say `this`, you're actually refferencing the AJAX object
        // And not the getData object.
        self.myData = data;
    });

    return myData;
};
Akar
  • 5,075
  • 2
  • 25
  • 39