I have faced the same problem many times where the translation has to be handled with JavaScript. The best solution I came up with is to send translation object from the server to the front-end. I will give you an example
First create folder with translation files. Than create another file where you can handle the translation. It purpose is to generate a JavaScript object which will be send to the front-end. In my case it was a PHP server so I created a file named translation.js.php
/languages/en.php
<?php
$_GET['FILTER'] = [
"hello_world" => "Hello World",
"result" => "result",
"all" => "all",
"brand" => "brand"
];
/languages/bg.php
<?php
$_GET['FILTER'] = [
"hello_world" => "Здравей Свят!",
"result" => "ресултати",
"all" => "всички",
"brand" => "марки"
];
/translation.js.php
<?php
// define the posibile languages you can have
$languages = array('en', 'bg', 'fr', 'es');
//set the language from $_GET parameter or any other technique to set the lang
$client_lang = $_GET['lang']; //I am not sure if this parameter has to be escaped
//check if you have the requested language
if(in_array($client_lang, $languages) {
require_once "languages/" . $client_lang . ".php";
} else { //if the client language is not in languages array, set the default language
require_once "languages/en.php";
}
$translation = <<<EOT
var translate = {
hello_world: "{$_GET['FILTER']['hello_world']}",
results: "{$_GET['FILTER']['results']}",
all: "{$_GET['FILTER']['all']}",
brand: "{$_GET['FILTER']['brand']}"
}
EOT;
echo $translation;
Than in your header of footer include the translation.js.php file depending on your business logic. In my case I needed to translate only content which was dynamically create with JavaScript so I handled it the the footer.php file
...
<script><?php require_once "translation.js.php" ?></script>
<!-- then include your main js file which will assume that the translation object exists -->
<script src="<?php echo PATH_R ?>views/assets/js/main.js"></script>
And last you main.js file
console.log(translate)
// how lets set the heading using jQuery
$('h1#main_heading').html(translate.hello_world)