How can I force a synchronous $.get call to load contents of a file into a variable?

976 Views Asked by At

I understand how $.get() fetches asynchronously. But how can I force a synchronous call?

I require preferences loaded from a json file to be used throughout many javascript calls throughout an app. How can I load these preferences not into the DOM, but rather a variable to be used throughout the rest of the app?

Here's how it works asynchronously:

$.get('my.json',function(data) { var myJson = data; });
console.log(myJson); // undefined
$('.myElement').html(myJson.title); // this will asynchronously load the contents of myJson.title into `.myElement`

I've read that I should try:

$.get('my.json',WrapperFunction(data));
WrapperFunction(data) {
    // do all of your javascript calls here
}
console.log(myJson); // undefined

Any other ideas to not move on until get completes?

3

There are 3 best solutions below

1
kcsoft On BEST ANSWER
  1. You need to declare your myJson var outside the function scope function(data) { var myJson = data; }); or else it will not be visible to other functions.

    var myJson; $.get(...);

  2. Synchronous ajax calls are bad. You don't need that. All you need is that when the data is available to notify other parts of your app.

var myJson;
$.get('url.json', function(data){
    myJson = data;
    dataIsAvailable();
});

function dataIsAvailable() {
 ... you can use myJson here
}
4
blurfus On

Example from the docs:

$.get( "my.json", function( data ) {
  console.log( data );
  var myJson = data;  // or whatever your data's format is
  console.log( "Title: " + myJson.title );
  $('.myElement').html( myJson.title ); // or whatever your data's format is
});

notice the console is inside the function() instead of outside as you had it.

updated example

0
ZippyV On

You are declaring your variable in the wrong place. If you want the variable to be available to multiple functions you have to declare it outside of those functions. You don't need to run the request synchronously to achieve what you want.

var mySettings;

$.get('my.json',function(data) { mySettings = data; });

function showSettings() {
    alert(mySettings);
}