The website I’m currently working on is written into two languages (fr/en). The method I’m using to translate the page is quite simple :
HTML
<ul id="switch">
<li><a href="index.php?lang=en" title="English version">En</a></li>
<li><a href="index.php?lang=fr" title="Version française">Fr</a></li>
</ul>
PHP (index.php)
<?php
// Translation
if(isset($_GET['lang'])) {
$lang = $_GET['lang'];
}
else {
$lang = 'en';
}
switch($lang) {
case 'en':
$content = 'en.php';
break;
case 'fr':
$content = 'fr.php';
break;
}
include_once('lang/'.$content);
?>
Both en.php and fr.php contain an array filled with the actual content of the page in their respective language.
en.php (example)
<?php
$version = array(
'mainTitle' => 'Main title test',
'noscript' => 'Noscript message test',
'header' => 'Header test'
// And so on, same thing for the french version
);
?>
This system works fine and is sufficient for this website, but it implies a page refresh when the user switches from one language to another and that is precisely what I would like to avoid.
I guess I could work this out using a bit of AJAX (jQuery) but I am not exactly sure how to do this. Could you give me a few hint on how to implement this? I’m also open to suggestions on other possible ways of doing this – bearing in mind that it is a small scale project.
Thanks for your help.
I would suggest the following, keep your language specific stuff in a Javascript dictionary, have a Javascript method to populate data from that dictionary, have a PHP server call which returns you contents for that dictionary (basically your language-specific content) and whenever user switches to a different language, make that PHP server call to populate your Javascript dictionary and call your Javascript method to populate.
Roughly, it would be something like this
You could call this method at page load or you could still load it from php at first load
You should call this method whenever user changes language e.g.
Note: You should include jquery
Note2: See jQuery get for proper syntax of $.GET
However, this is unnecessarily complex for just language switching. Similarly, you could load the entire page in AJAX and set your body to the newly loaded page based on language. Depends on whichever is easier for you to provide as a service call (providing only language dictionary vs. providing entire page in a specific language) For the latter, see jQuery load