0

I have the following javascript code:

function initSite(){
    var site;
    $.getJSON(www+'init/initSite', function(data) { site = data; });
}
$(document).ready(function(){
    var site = initSite();
        console.log(site);
}

which returns undefined... how can i store the json object that i recieve in the site variable so i can use it later?

EDIT: This seem to work but im not sure if its correct to use this solution

var site = null;
$.ajax({
  url: www+"init/initSite",
  async: false,
  dataType: 'json',
  success: function (data) {
    site = data;
  }
});
console.log(site);
stergosz
  • 5,754
  • 13
  • 62
  • 133

3 Answers3

1
function initSite(onSuccess){
    $.getJSON(www+'init/initSite', onSuccess);
}
$(document).ready(function(){
   initSite(function(data){
       var site = data;
       // initialize your code.
   });
}
driangle
  • 11,601
  • 5
  • 47
  • 54
  • my current javascript code is over 2000 lines of code... do i have to put all the code where you call the function? – stergosz Feb 08 '12 at 17:48
1

The problem is just a miss concept:

getJSON is an async call, and the site = data; will only happen way after the DOM is ready.

in order for you to make everything work the way it should, your initialization needs to start from your async call result and never before, for example:

// no need to wait for DOM ready to call `initSite`
initSite();

function initSite() {
    $.getJSON(www+'init/initSite', function(data) {  
        initialization(data);
    });
}
function initialization(site) {
    // initialize all the things that need to be done
    console.log(site);
}

$(document).ready(function(){
    // do other stuff, for example show a loading message/image
}
balexandre
  • 73,608
  • 45
  • 233
  • 342
1

of course you got undefined because your function doesn't return anything and the ajax call is also asynchronous, so you have to wait the server response. Since $.ajax (and shortcuts) returns a promise you can do this task using deferred

function initSite(){
    return $.getJSON(www+'init/initSite');
}
$(document).ready(function(){
    $.when(initSite()).done(function(data) {
        /* continue here the code execution, e.g. call another function */

        doAllTheRemainingWorkWith(data)

    });
}

as you can see this code is short and easy to read

Fabrizio Calderan
  • 120,726
  • 26
  • 164
  • 177