JavaScript is a browser tool to add dynamics to your content. Content is what your server returns and it is up to you to decide how you are going to store that data.
The most of the data you will store in the database including translations for your models.
UI texts can be stored in simple files, however, they are stored often in DB as well.
Yes, sometimes you need to handle translation using a JavaScript. For example, to change the label of the button when user clicks on it. In most cases what you will do is just an AJAX request and server will return what you need.
friendBtn.addEventListener('click', () => {
fetch(`/ajax/users/send-friend-request/${friendBtn.dataset.id}`)
.then(response => {
return response.json();
})
.then(data => {
if (data.status = 'ok') {
// data.data.requestSent contains "Friend request peding" in current locale
friendBtn.textContent = data.data.requestSent;
}
// ...
});
});
The general case how to pass data from server to JavaScript is to generate a global variable on the server. Below is example for PHP (I prefix all data in superglobal Server like Server.user, Server.lang, Server.settings, Server.env, whatever):
// global template
<script>
var Server = {};
var Server.lang = {};
</script>
// page where you need translated data
<script>
// trans() function returns data from certain file in current app locale
<?php foreach (trans('users') as $key => $val) : ?>
Server.lang.<?php echo $key; ?> = '<?php echo $val; ?>';
<?php endforeach; ?>
</script>
// P.S. you may also use json_encode() or escape $val to prevent XSS
Can you provide a use-case where you have a dynamic and that dynamic is not related to AJAX and you need to change your text, how exactly?