最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Dynamically switching language PHP,Javascript, jQuery UI - Stack Overflow

programmeradmin2浏览0评论

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 ing 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?

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 ing 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?

Share Improve this question asked Jun 10, 2013 at 1:27 DimitriDimitri 1,9763 gold badges26 silver badges50 bronze badges 4
  • 1 Why not have javascript read the cookie and then based on that, download the correct localization file? – Dave Chen Commented Jun 10, 2013 at 1:29
  • i think effective method can be extracting lang cookie information by the datepicker.js and loads accordingly – progrrammer Commented Jun 10, 2013 at 1:30
  • Hmm, loading the cookie would be an option.. – Dimitri Commented Jun 10, 2013 at 1:31
  • Il assume making all of the pages with PHP isn't an option, your only other option is to use javascript to load the language specific files. <hr> Or here is an artical on redirecting from the htaccess. You can redirect the en file to go to the fr file based on the cookie and could also redirect based on get values! Good luck, let me know how you get on! – Charlie Walton Commented Jun 10, 2013 at 1:38
Add a ment  | 

6 Answers 6

Reset to default 1

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.

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>

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 mon js file and I would call the getLang() function on all of my pages...

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;
});

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 acplish the task this way, I would highly remend switching all your pages to php, as it would simplify things like this one.

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.

发布评论

评论列表(0)

  1. 暂无评论