I have a multi-language project with Laravel.
I want to localization for JavaScript files.
first I create this function to get an array of translations from a PHP server.
function lang(type){
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var langs = JSON.parse(this.responseText);
console.log(langs); // it works!
return langs;
}
};
xhttp.open("GET", "/renders/langs?type="+type , true);
xhttp.send();
}
lang function
works and it returns an array of strings as expected
now I want to call that function in every other function that I want.
for example, I have a function like this:
(function(){
document.addEventListener("DOMContentLoaded",function(){
document.querySelectorAll('form.destroy').forEach(e =>{
e.addEventListener('submit', function(event) {
event.preventDefault();
var langs;
langs = lang('destroy');
console.log(langs);// not work!...it returns null!
alert(langs['delete_file_message');
});
});
});
})();
Can you please tell me what's wrong and how to correct the code?