Meek
Meek

Reputation: 3362

jQuery ajax object syntax error

I'm using Datatables.js to handle a large table with a lot of data. I'm trying to add some custom languages, but I keep getting a object syntax error when handling the language file: http://domaintest.com/[object%20Object].

If I comment the ajax call, there's no error.

The error is visible in the console here: jsFiddle.

The code:

function runDatatable() {
  // Datatable language switcher with custom language mods to overwrite the defaults
  function getLanguage() {
    var $langMap = {
      en: {
        path: 'English',
        mods: {
          sLengthMenu: 'Display _MENU_ persons',
          sInfo: 'Showing _START_ to _END_ of _TOTAL_ persons',
          sInfoEmpty: 'Showin 0 to 0 out of 0 persons'
        }
      },
      es: {
        path: 'Spanish',
        mods: {
          sInfo: "Mostrando registros del _START_ al _END_ de un total de _TOTAL_ personas",
          sInfoEmpty: "Mostrando personas del 0 al 0 de un total de 0 personas"
        }
      }
    };
    var $lang = $('html').attr('lang');
    // Fallback
    if (!$langMap[$lang]) {
      $lang = 'en';
    }
    var $result = null;
    var path = '//cdn.datatables.net/plug-ins/1.10.13/i18n/';
    var url = path + $langMap[$lang].path + '.json';
    console.log(url);
    $.ajax({
      async: false,
      url: url,
      success: function(obj) {
        $result = $.extend({}, obj, $langMap[$lang].mods);
        console.log($result);
      },
      error: function(xhr, status, error) {
        console.log(xhr.responseText);
      }
    });
    return $result;
  }

  // Build Datatable
  $('#datatable').DataTable({
    language: {
      url: getLanguage()
    },
    ordering: true,
    autoWidth: false,
    fixedHeader: true,
    responsive: true
  });
}

What am I missing here?

Upvotes: 0

Views: 86

Answers (1)

NikNik
NikNik

Reputation: 2301

You should extend you object in this way:

   $tmp = $.extend({}, obj, $langMap[$lang].mods);
   $langMap[$lang].mods = $tmp;

and you are asking for url:

 language: {
      url: getLanguage()
    },

but you return $langMap

so you should something like (without ajax call):

return path + $langMap[$lang].path + '.json';

https://jsfiddle.net/j6w5ww7w/1/

and the last one if you want to override the standard file:

language: getLanguage() and return $langMap[$lang].mods;

https://jsfiddle.net/j6w5ww7w/3/

Upvotes: 1

Related Questions