I have this code:
var languageCode = {};
$.ajax({
url: 'languages/en.xml',
success: function(xml) {
$(xml).find('string').each(function() {
languageCode[$(this).attr('name')] = $(this).text();
console.log(languageCode.IDSA_HI_THERE); // This works
});
console.log(languageCode);
}
});
console.log(languageCode.IDSA_HI_THERE); // This doesn't work because this gets called before the ajax request. How to make this work without using "async: false"?
Any idea?
Thanks, Klevis
Use the Promise:
JQuery >= 3.0:
const promise = $.ajax({...}) promise.then(() => console.log(languageCode.IDSA_HI_THERE))or for native Promise:
const promise = Promise.resolve($.ajax({...})) promise.then(() => console.log(languageCode.IDSA_HI_THERE))JQuery < 3.0:
var promise = $.ajax({...}); promise.done(function() { console.log(languageCode.IDSA_HI_THERE); }); //or promise.always(...);or for native Promise:
var promise = new Promise(function(resolve, reject) { $.ajax({ ..., success: function(xml) { ...; resolve(); }, error: function() { reject(); } }); }); promise.then(function() { console.log(languageCode.IDSA_HI_THERE); });