Search code examples
javascriptajaxdatatables

Localization in Ajax Datatable


I am trying to figure out a way to display Datatable language based on the local language of the Server/PC. The idea is that based on the language it should load the respective language file.The question may sound trivial, but i dont have much JavaScript experience. After some hours of Internet research thought i could use something like that:

  if ( $.fn.dataTable.isDataTable( '#systemStatusTable' ) ) {
                datatable = $('#systemStatusTable').DataTable({
                 var userLang = navigator.language || navigator.userLanguage;
                    if (userLang.startsWith("de")) {
                        language: {
                               url: 'https://cdn.datatables.net/plug- 
                                                                  
                               ins/1.10.20/i18n/German.json'                                                      
       }
                          }
                       }

                });

but it give me error on the line with userLang - Unexpected Identifier UserLang

Also generally i am not quite sure if this will work this way or if its the best option to achieve that goal.Any tips ? Thanks in advance


Solution

  • Your if-statement can not be inside datatables initialization.

    This is how to make it :

       var lang = 'English';
       var userLang = navigator.language || navigator.userLanguage;
       if (userLang.startsWith("de")) {
         lang = 'German';
       }
       var datatable = $('#systemStatusTable').DataTable({
           "language": {
                "url": "https://cdn.datatables.net/plug-ins/1.10.20/i18n/"+lang+".json"
            }
        });