1

I need to use a function several times and wanted to avoid writing the same method over and over. I wanted to use $.getJSON() response and store it in a var that will be returned. That way I can just call the method.

function startFilter(){
            var grid = [];
            $.getJSON('data/gridData1.json',function(json){
                grid = json;
                console.log(grid);
            });
            console.log(grid);
            return grid;
        }

the grid var is set inside of the .getJSON but not outside of .getJSON. any ideas why, and if more info is needed let me know?

user2812097
  • 92
  • 2
  • 14
  • 6
    Ajax is async. The return statement happens before the `grid = json` statement. – Jason P Sep 24 '13 at 18:20
  • To expand on what @JasonP said, you can use $.ajax instead and add the `async=false` option if you want, although you'd be better of structuring your code to be asynchronous. Perhaps passing a callback function into `startFilter` that then takes your grid. After the call completes, you could call the callback function with the grid and then the callback could perform whatever action you want with the grid. – Pete Sep 24 '13 at 18:22

2 Answers2

3

The Ajax calls are async. Here is how the things are positioned in the time.

function startFilter(){
    var grid = []; // (1)
    $.getJSON('data/gridData1.json', function(json){  // (2)
        grid = json;  // (5)
        console.log(grid); // (6)
    });
    console.log(grid);  // (3)
    return grid;  // (4)
}

You should use callbacks to build your logic:

function startFilter(callback) {
    $.getJSON('data/gridData1.json', callback);
}

var grid = [];
startFilter(function(json) {
    grid = json;
    // your logic here
});
Krasimir
  • 13,306
  • 3
  • 40
  • 55
0
var grid;

function startFilter(dataReady ){
        var grid = [];
        $.getJSON('data/gridData1.json',function(json){
            grid = json;

             dataReady () ; 
        });
        console.log(grid);
        return grid;
    }

startFilter ( function () {
console.log(grid);
} ) ; 
sino
  • 754
  • 1
  • 7
  • 22