Is it possible to assign data to a global variable from a jquery get? Here is a very simplified version of what I am trying to do.
var page;
$.get( "view/tenantHome.html", function(data){page = data;});
console.log(page);
There are 2 ways
Async (recommended):
var page;
$.get( "view/tenantHome.html", function(data){
page = data;
console.log(page);
});
Sync (not recommended);
$.ajaxSetup({async: false});
var page;
$.get( "view/tenantHome.html", function(data){ page = data; });
console.log(page);
$.ajaxSetup({async: true});
The second one is not recommended because it will block script execution until the ajax call finishes. However, there are some cases when you might need it.
Hope this helps. Cheers
The $.get is a shorthand method for doing AJAX in jQuery. These methods are asynchronous by default, so what you're running in to can be called a race condition. I think you'll want to read up on these concepts as you continue developing in jQuery and use AJAX.
$.get has an option for a callback parameter which will get called once the response is received, that callback is shown in your original code.
var page;
$.get( "view/tenantHome.html", function(data){page = data;});
console.log(page);
You can do something simple like encapsulate the code that depends on the page variable in a function.
var page;
$.get( "view/tenantHome.html", function(data){
page = data;
codeThatDependsOnPageVariable();
});
function codeThatDependsOnPageVariable() {
console.log(page);
}
In that way you can call the code block once you have ensured you have the necessary data.
.get() function returns deferred object which contains callbacks .done(), .fail(), .always(). Now you handle only done callback and you don't know about fails. Use this:
$.get('view/tenantHome.html').done(function(result){
page = data;
console.log(page);
}).fail(function() { console.log('Request fail'); });
Now you can handle fails.
Never use async: false in production, while request in progress your page will frozen, and often all tabs in browther is frozen.
console.log()line. In fact, 99.9% of the time it won't.