Latey I’ve got some trouble with some weird javascript behavior. I want to do something like this:
var lang = null;
function getLang() {
if (browserLanguageIsGerman) {
lang = 'de';
}
else {
lang = 'en';
}
// alert(lang) shows "de"
$('#someID').load(someValidUrl, null,
function(response, status, xhr) {
if(languageSettingsOnFacebookIsGerman) {
lang = 'de';
}
else {
lang = 'en';
}
// alert(lang) show "en"
);
// alert(lang) shows "de"
}
The first and the second alerts show the expacted value 1) “de” 2) “en”. The third alert shows “de” but shouldn’t it be “en”?!
Also the second alert pops up after the third alert.
Can someone please obvious bug in my mind? 🙂
Thanks in advance!
This is not an issue with scope. The
loadmethod is asynchronous. The thirdalertis executed before the callback you pass toload. Move any code that depends on the result of that async call into the callback.Alternatively, you can look into the jQuery deferred objects API. Note that if you were to use the deferred object API you would need to change you call to
loadto a call tojQuery.getorjQuery.ajax, since.loadreturns an instance of jQuery, which doesn’t implement the Promise interface.