Magento Stack Exchange is a question and answer site for users of the Magento e-Commerce platform. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I am trying to use the jquery DataTables in magento-2 frontend using the requirejs. I can see the datables.min.js file in the net panel, enter image description here

but somehow it give the following error.
enter image description here

My reuirejs-config.js looks like this

var config = {
    map: {
        '*': {
            dataTable: 'Ktpl_Slider/js/datatables.min'
        }
    }

};

And i am calling this function in a template file as follows

<script type="application/javascript">
    requirejs(['jquery','dataTable'],function($){
        $(document).ready(function(){
            $('#list-table').DataTable();
        });
    });
</script>

I guess there is problem with the order of loading the js files. i tried with shim configuration but that did not work, maybe there was some mistake in the shim configuration

share|improve this question

You can add jquery with your script in template file no need to add dependency in reuirejs-config.js

I have put my script here please try this.

<script type="text/javascript">
require(['jquery', 'DataTable'],function($){
    (function() {
         $('#relatedProductTable').DataTable({
              "aaData":<?php echo json_encode($dataProducts);?>,
              "aoColumnDefs":[{
                    "sTitle":"Site name"
                  , "aTargets": [ "site_name" ]
              }]);
                    })(jQuery);
});

share|improve this answer

I think that you have another problem in your script. you have defined both jquery and datatable as dependencies. But you only pass jquery to the function. The function part of the requirejs script should have the dependency scripts object passed to the function part. try:

<script type="application/javascript">
requirejs(['jquery','dataTable'],function($, dataTable){
    $(document).ready(function(){
        $('#list-table').DataTable();
    });
});

As for the shim part, I think that if you have defined it something like :

var config = {
    map: {
        '*': {
            dataTable: 'Ktpl_Slider/js/datatables.min'
        }
    },
    "shim" {
        "dataTable" : ["jquery"]
    }
};

then it's fine. Looks like it works for me, however, the extra quotes around "shim" are only present in Magento 2 documentation, and not in requirejs documentation. so not sure which one is right.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.