jquery - How to load the initial data before the rest of the javascript code runs? -


i cant figure out how load server essential initial data used rest of javascript code after $(document).ready(function(){.

in concrete terms:

in index.html have

<head> <script type="text/javascript" src="js/data.js"></script> ...   $(document).ready(function(){         initialize();         console.log(grantsdata);  ... 

this returns firebug console "grantsdata undefined"

in file data.js have

var grantsdata; $.getjson( "js/mysql_query_grants2.php", function(json){         alert("got sql data json");         grantsdata = json;                 console.log(grantsdata);                 } 

this returns console expected.

questions:

does infer .getjson() did not chance finish returning grantsdata result before code ran in index.html?

how can change key initial grantsdata loaded, after initialize(), but before other javascript depends on data in run?

what alternative non-ajax getjson()?

stay asynchronous.

$(document).ready(function(){         // 1          initialize_everything(function() {             // 6             console.log(grantsdata);             ...         });          // 4   } 

in data.js:

function initialize_everything(callback) {     // 2     $.getjson( "js/mysql_query_grants2.php", function(json){         // 5         // ...          // have everything, report         callback();         }     }      // 3 } 

does infer .getjson() did not chance finish returning grantsdata result before code ran in index.html?

it's asynchronous, processes data (i.e. runs code passed it) server's response arrives. in meantime, browser continues execute javascript, $(document).ready() callback invoked though other, unrelated ajax request may not have completed yet. if rely on timing of callbacks, app might behave differently in different browsers or fail randomly.

the heavy use of closures (i.e. local function() {}s passed around , invoked later) javascript's idiomatic way deal asynchronous program flow.

edit: clarify this, added possible execution order above sample.


Comments

Popular posts from this blog

apache - Add omitted ? to URLs -

redirect - bbPress Forum - rewrite to wwww.mysite prohibits login -

php - How can I stop spam on my custom forum/blog? -