Dimitri
Dimitri

Reputation: 1966

Dynamically switching language PHP,Javascript, jQuery UI

I recently started implementing language options for my website. Here is how it basically works:

if(isset($_GET['lang']))
{
    $langr= $_GET['lang'];
    $_SESSION['lang'] = $langr;
    setcookie('lang', $langr, time() + (3600 * 24 * 30));
}
elseif(isset($_SESSION['lang']))
{
    $langr = $_SESSION['lang'];
}
elseif(isset($_COOKIE['lang']))
{
    $langr = $_COOKIE['lang'];
}
else
{
    $langr = 'en';
}
switch ($langr) 
{
  case 'en':
  $lang_file = $_SERVER['DOCUMENT_ROOT']."/includes/lang/en.php";
     break;
  case 'fr':
  setlocale (LC_ALL, 'fr_FR.utf8','fra'); 
  $lang_file = $_SERVER['DOCUMENT_ROOT']."/includes/lang/fr.php";
     break;

  default:
  $lang_file = $_SERVER['DOCUMENT_ROOT']."/includes/lang/en.php";

}
include_once $lang_file;

It loads the appropriate language file at the top of every page in my website. However, issues starting coming out when using jQuery's UI datepicker. I found a regional settings file for the datepicker online and have created a separate file for it :

///jquery.ui.datepicker-fr.js  file

jQuery(function($){
    $.datepicker.regional['fr'] = {
        closeText: 'Fermer',
        prevText: 'Précédent',
        nextText: 'Suivant',
        currentText: 'Aujourd\'hui',
        monthNames: ['janvier', 'février', 'mars', 'avril', 'mai', 'juin',
            'juillet', 'août', 'septembre', 'octobre', 'novembre', 'décembre'],
        monthNamesShort: ['janv.', 'févr.', 'mars', 'avril', 'mai', 'juin',
            'juil.', 'août', 'sept.', 'oct.', 'nov.', 'déc.'],
        dayNames: ['dimanche', 'lundi', 'mardi', 'mercredi', 'jeudi', 'vendredi', 'samedi'],
        dayNamesShort: ['dim.', 'lun.', 'mar.', 'mer.', 'jeu.', 'ven.', 'sam.'],
        dayNamesMin: ['D','L','M','M','J','V','S'],
        weekHeader: 'Sem.',
        dateFormat: 'dd/mm/yy',
        firstDay: 1,
        isRTL: false,
        showMonthAfterYear: false,
        yearSuffix: ''};
    $.datepicker.setDefaults($.datepicker.regional['fr']);
});

The issue is I need to dynamically load jquery.ui.datepicker-fr.js whenever a language change is detected so that my datepicker switches to french. What I was thinking is creating a PHP function that I would put in my <head> that would echo out my file, but the problem with that is that not all my web pages are PHP and I don't find this a very effective method. Any other ideas on how to do this?

Upvotes: 6

Views: 2758

Answers (6)

Dendromaniac
Dendromaniac

Reputation: 394

Improved version of Moeed's answer:



You need to put a check in your header.php which will goes like that:

<script src="/js/<?php echo 'datepicker-' . *COOKIE/SESSION VALUE, LIKE en* . '.js'; ?>"></script>

This will dynamicly select datepicker-???.js where ??? is the value represented by the cookie/session-cookie.

Upvotes: 0

Borik
Borik

Reputation: 438

I would do this way, have a separate PHP file responsible for getting correct JS File, this way you can use it in plan HTML pages as well...

<script type="text/javascript" src="/getCorrectJsFile.php"></script>

Upvotes: 1

ZurabWeb
ZurabWeb

Reputation: 1368

You could use jQuery cookie plugin, a good one. Then do same procedure with jQuery as with php. If language supplied as url parameter - set cookie with the plugin (get language value with the getBaseURL() function above). Otherwise load cookie and then load appropriate javascript file. Something like $('head').append('<script..'); should do the task.

Make sure to run this whole script on page load with $(function() { /* code here */ });

Although it's possible to accomplish the task this way, I would highly recommend switching all your pages to php, as it would simplify things like this one.

Upvotes: 0

Moeed Farooqui
Moeed Farooqui

Reputation: 3622

You need to put a check in your header.php which will goes like that:

<script type="text/javascript>" src="/js/<?php if($_SESSION['lang'] == "en"){ echo 'datepicker-en.js'}else echo 'datepicker-fr.js'; ?>"></script>

So it will automatically detect the datepicker file according to your language parameter.

Upvotes: 1

shin
shin

Reputation: 32721

How about using .change() and .post()? You add id of lang to your form where a user can change the language.

$('#lang').change(function(){
           //link to your php file
    var findlangfile = "<?php echo index.php/findlang.php;?>
    $.post(findlangfile, {
        lang: $('#lang').val(),
    }, function(response){
        // you do things
    });
    return false;
});

Upvotes: 0

Dimitri
Dimitri

Reputation: 1966

What do you think of this approach?

function getBaseURL()
{
    var url = location.href;
    var baseURL = url.substring(0, url.indexOf('/', 14));
    if (baseURL.indexOf('http://localhost') != -1)
    {
        var url = location.href; 
        var pathname = location.pathname;  
        var index1 = url.indexOf(pathname);
        var index2 = url.indexOf("/", index1 + 1);
        var baseLocalUrl = url.substr(0, index2);
        return baseLocalUrl + "/";
    }
    else
    {
        return baseURL + "/";
    }
}

function getCookie(c_name)
{
    var i,x,y,ARRcookies=document.cookie.split(";");
    for (i=0;i<ARRcookies.length;i++)
    {
        x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
        y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
        x=x.replace(/^\s+|\s+$/g,"");
        if (x==c_name)
        {
            return unescape(y);
        }
   }
}


function getLang()
{
    var lang = getCookie("lang");
    switch(lang)
    {
        case "fr":
            document.write("<script src='"+getBaseURL()+"js/lang/jquery.ui.datepicker-"+lang+".js'></script>");
            break;
        default:
            document.write("");
    }
}
getLang();

The functions would be located in a common js file and I would call the getLang() function on all of my pages...

Upvotes: 0

Related Questions