Zbarcea Christian
Zbarcea Christian

Reputation: 9548

How to insert in javascript file php variables?

My page is available in 3 languages and I'm including in the header of each file (index, contact, etc.) the selected language file (en, ru, pl).

<?php
session_start();
include('language/'.$_SESSION['lang'].'.php');
?>

en.php

<?php
session_start();
$lang = array();

$lang['hello'] = 'Hello';
$lang['world'] = 'World !';
?>

ru.php

<?php
session_start();
$lang = array();

$lang['hello'] = 'привет';
$lang['world'] = 'мир';
?>

And this is how I'm echoing them:

<p><? echo $lang['hello'].' '.$lang['world'];?></p>

This is working actually fine, but I'm having problem with my .js files. If I want to alert or insert some text somewhere I can't.

For example in one of my .js file I have an alert:

if (something_obj.val() == ''){
   alert('Wrong username given !');
   return false;
}

How can I implement language files in my js files? Am I need to create a news .js language file?

Upvotes: 0

Views: 1343

Answers (2)

hsz
hsz

Reputation: 152206

You can create new file - for example js.php which will load proper language file and print out all variables into JavaScript array:

js.php

<script type="text/javascript">
var lang = {
<?php
session_start();
include('language/'.$_SESSION['lang'].'.php');

$data = array();
foreach ( $lang as $key => $value ) {
  $data[] = '"' . $key . '" : "' . $value . '"';
}
echo implode(',', $data);
?>
};
</script>

Then include this file on the page which have to use JavaScript translation array and use it with:

alert(lang.key);

Also if there will be " sign in the translation string, you have to escape it with \", for example with:

$value = str_replace('"', '\"', $value);

Upvotes: 1

thejh
thejh

Reputation: 45568

You could have one js file per language with translations looking like this:

// german.js
var translations = {
  'hello': 'hallo',
  'world': 'welt'
};

In other JS scripts, just do something like this:

alert(translations['hello'] + " " + translations['world'])

Of course, you might want to choose a shorter variable name than translations.

Then, in your php file, include the correct JS script based on the language:

<script src="languages/<?php echo $_SESSION['lang']; ?>.js"></script>

Upvotes: 3

Related Questions