8

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

6

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.

|improve this answer|||||
6

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

|improve this answer|||||
  • can you please share me full code to include datatables plugin into magento2? – jafar pinjar Oct 17 '18 at 9:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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