I have an application mainly written in PHP. The translations are done using gettext().
There is a small JavaScript part which also contains strings to be translated. I wrote this simple but working method using XMLHttpRequest:
function gettext(string_to_translate) {
var filename = get_php_script_folder() + 'gettext.php?string_to_translate=' + string_to_translate;
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", filename, false);
xmlhttp.send();
if (xmlhttp.status === 200) {
var translated_string = xmlhttp.responseText;
return translated_string;
} else {
console.log("Error while translating " + string_to_translate + " Status " + xmlhttp.status);
return string_to_translate; //Just give the original string.
}
}
The php file is also quite simple:
require_once '../../default.php'; //configures gettext, session management, etc.
//TODO: support for ngettext might be added.
$string_to_translate = filter_input(INPUT_GET, 'string_to_translate', FILTER_SANITIZE_STRING);
$translated_string = gettext($string_to_translate);
echo $translated_string;
In the JavaScript I just call:
var input_box_form_default_reason = gettext("Vacation");
document.getElementById('input_box_form_reason').value = input_box_form_default_reason;
If I call this function synchronously [xmlhttp.open("GET", filename, false);] Firefox/Chrome warns me that:
[Deprecation] Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. For more help, check https://xhr.spec.whatwg.org/.
So while this method works, it may cease to do so at any time.
But if I run the code async [xmlhttp.open("GET", filename, true);], then the next line will be executed before the result is there. The value will be undefined.
Is it feasable to make async XMLHttpRequest work in this context? Should I stick to synchronously fetching the values until some clever API is written? Should I write my JS files with PHP? (I hope not.)
PS:
I do not use any framework like jQuery. That is a "religious" thing. I want to fully understand and maintain the whole codebase myself.
I read the following questions, which did not answer mine: