• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar
seegatesite header

Seegatesite.com

Seegatesite.com - Programming Tutorial , Sharing , How and Learn Together

  • TOOLS
    • Bootstrap Navbar Online Generator
    • Customize Sidebar Menu Bootstrap 3
    • Bootstrap Demo
  • ADVERTISE
  • CATEGORIES
    • Android
    • Blogging Tips
    • Database
    • CSS
    • Info Gadget
    • Javascript
    • Linux
    • PHP
    • Various
    • WordPress
  • Q&A
  • PHP
  • JAVASCRIPT
  • JQUERY
  • ANGULAR
  • WORDPRESS
  • SEO
  • REACT
🏠 » Javascript » Adept Using Datatables Plugin In 10 Minutes For Beginners (Tutorial)

Adept Using Datatables Plugin In 10 Minutes For Beginners (Tutorial)

By Sigit Prasetya Nugroho ∙ October 10, 2020 ∙ Javascript ∙ Leave a Comment

Share : TwitterFacebookTelegramWhatsapp

Datatables is a mandatory plugin for presenting information in HTML tables, especially for web applications or Point Of Sales Application. If you become proficient at using Datatables, creating, web applications will be faster and more efficient. I’m going to share some techniques for using datatables that I’ve been using so far that are easy to understand. Follow the following tutorial.

Obviously, this article doesn’t need to explain what Datatables is ?; I’m sure everyone reading this article understands it. Many blogs also discuss it in detail and can also be read in full on the official website.

What will I discuss here?

  1. Make the default settings for Datatables.
  2. Adding data sources to Datatables.
  3. Datatables option is most often used.
  4. Retrieve all data objects in Datatables via table rows.

Let’s just get started.

Related Articles :

  • Tutorial CRUD PHP, MySQL And JQuery In 10 Minutes (Bonus Source Code)

Tutorial Datatables In 10 Minutes For Beginners

Table of Contents

  • 1 The complete Datatables guide for beginners
    • 1.1 1. Make the default option setting on Datatables.
    • 1.2 2. Adding data sources to Datatables.
    • 1.3 3. The most options are frequently used for datatables.
    • 1.4 4. Retrieve all data in datatables via table rows selection.
  • 2 Datatable Examples Demo
  • 3 Conclusion

The complete Datatables guide for beginners

1. Make the default option setting on Datatables.

This is important. Large applications usually display a table on each HTML page. Setting the default option for Datatables will speed up writing code and minimize lines of code. The large files that are formed automatically are smaller and speed up the rendering of the application.

This default is written only once; make sure it is written in a separate file and called on every web page that requires Datatables. Write down the default datatables option settings as follows.

1
2
3
4
5
6
7
8
9
10
11
12
$.extend(true, $.fn.dataTable.defaults, {
        paging: false,
        lengthChange: false,
        searching: false,
        processing: true,
        ordering: false,
        info: false,
        responsive: false,
        autoWidth: false,
        pageLength: 10,
        dom: '<"top"f>rtlip'
      });

So calling the Datatables code simply calls the “columns” option, which is used to manage the data fields’ location. Check out the following example :

1
2
3
4
$("#table-data").DataTable({
        data: data_table, // data array object
        columns:  // column declaration
      });

2. Adding data sources to Datatables.

How do you insert data into a data table? There are 3 ways I most often use to add data to the Datatable, namely data sources options, draw tables method, and AJAX method. These three methods are relatively easy to use, but using AJAX makes the application smoother when data changes occur.

Displays data on the Datatable via the “data” option. The input data is an array of objects

for example, we have array object data as follows.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
let data_table = [
    {
      "id": 1,
      "name": "Kurtis Weissnat",
      "username": "Elwyn.Skiles",
      "email": "Telly.Hoeger@billy.biz",
      "phone": "210.067.6132",
      "website": "elvis.io",
    },
    {
      "id": 2,
      "name": "Nicholas Runolfsdottir V",
      "username": "Maxime_Nienow",
      "email": "Sherwood@rosamond.me",
      "phone": "586.493.6943 x140",
      "website": "jacynthe.com",
    },
   //..... another data
  ]

You need to add “data” to the datatables option as follows.

1
2
3
$("#table-data").DataTable({
        data: data_table,
      });

And the most important thing is to identify the individual column using the “column” option as follows.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
$("#table-data").DataTable({
        data: data_table,
        columns: [
          {
            data: null,
            render: function (data, type, row, meta) {
              return meta.row + 1;
            }
          },
          {
            data: "name,
          },
          {
            data: "data.address.street"
          },
          {
            data: "data.phone"
          }
        ]
      });

Add data using the draw table method

This method is good to displaying source data on Datatables. We don’t need to add “data” to the Datatables option. As an example :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
$("#table-data").DataTable({
         columns: [
          {
            data: null,
            render: function (data, type, row, meta) {
              return meta.row + 1;
            }
          },
          {
            data: "name,
          },
          {
            data: "data.address.street"
          },
          {
            data: "data.phone"
          }
        ]
      });
 
let data_table = [
    {
      "id": 1,
      "name": "Kurtis Weissnat",
      "username": "Elwyn.Skiles",
      "email": "Telly.Hoeger@billy.biz",
      "phone": "210.067.6132",
      "website": "elvis.io",
    },
    {
      "id": 2,
      "name": "Nicholas Runolfsdottir V",
      "username": "Maxime_Nienow",
      "email": "Sherwood@rosamond.me",
      "phone": "586.493.6943 x140",
      "website": "jacynthe.com",
    },
  ]
  let xtable = $("#table-data").DataTable();
  xtable.clear();
  xtable.rows.add(data_table);
  xtable.draw();

I created a method that is used to redraw the table in case of data changes.

1
2
3
4
5
6
const reDrawTable = (tablename, obj) => {
        let xtable = $(tablename).DataTable();
        xtable.clear();
        xtable.rows.add(obj);
        xtable.draw();
      };

Every time the data is a change in the target table, we just need to recall the above method and provide new data. Examples of use:

1
reDrawTable("#table-data",new_array_object);

The following example is retrieving data via API and adding it to Data table (Fetching data via API using the Axios library):

1
2
3
4
5
6
7
8
axios
.get("https://jsonplaceholder.typicode.com/users")
.then((result) => {
     reDrawTable("#table-data", result.data);
})
.catch((err) => {
    console.log(err);
});

Adding data to the Datatable using the “ajax” option.

This is the best way to add data source to the Datatable, in my opinion. The application becomes smoother when the data changes in the table.

examples of use:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
$("#table-data").DataTable({
        ajax: function (data, callback, settings) {
          axios
            .get("https://jsonplaceholder.typicode.com/users")
            .then((result) => {
              callback({ data: result.data });
            })
            .catch((err) => {
              console.log(err);
              callback({ data: [] });
            });
        },
        columns: [
          {
            data: null,
            render: function (data, type, row, meta) {
              return meta.row + 1;
            }
          },
          {
            data: null,
            render: function (data, type, row) {
              return data.name;
            }
          },
          {
            data: null,
            render: function (data, type, row, meta) {
              return data.address.street;
            }
          },
          {
            data: null,
            render: function (data, type, row, meta) {
              return data.phone;
            }
          }
        ]
      });

If the data is changed, you can refresh or reload the data with the following command

1
2
let table = $("#table-data").DataTable();
table.ajax.reload(null, false);

Or by creating a method that can be used at any time:

1
2
3
4
5
6
const refreshTable = (tablename) => {
        let table = $(tablename).DataTable();
        table.ajax.reload(null, false);
      };
 
refreshTable("#table-data");

There is one more dynamic way in my experience to add data to Datatable with the AJAX option. The idea is:

  • Create global variables to hold an array of objects with empty data

1
var array_data = [];

  • Attach a variable array object to the “ajax” option as follows

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
$("#table-data").DataTable({
        ajax: function (data, callback, settings) {
                       callback({ data: array_data });
        },
        columns: [
          {
            data: null,
            render: function (data, type, row, meta) {
              return meta.row + 1;
            }
          },
          {
            data: null,
            render: function (data, type, row) {
              return data.name;
            }
          },
          {
            data: null,
            render: function (data, type, row, meta) {
              return data.address.street;
            }
          },
          {
            data: null,
            render: function (data, type, row, meta) {
              return data.phone;
            }
          }
        ]
      });

  • Call the API and update data on global variables that we have previously set and refresh the data

1
2
3
4
5
6
7
8
9
10
axios
            .get("https://jsonplaceholder.typicode.com/users")
            .then((result) => {
              array_data =  result.data;
              refreshTable("#table-data")
 
            })
            .catch((err) => {
              console.log(err);
             });

3. The most options are frequently used for datatables.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
$("#table-data").DataTable({
        paging: true,
        lengthChange: true,
        searching: true,
        processing: true,
        ordering: true,
        info: true,
        responsive: true,
        pageLength: 10,
        dom: '<"top"f>rtip',
        ajax: function (data, callback, settings) {
            callback({ data: array_data });
        },
        createdRow: function (row, data, dataIndex) {
            
            if (parseInt(data.total) <= 0) {
                $(row).addClass("warning");
             }
        },
        fnDrawCallback: function (oSettings) {
            //call method after datatables ready
        },
        language: {
            lengthMenu: "Show _MENU_ record per-page",
            searchPlaceholder: "Search Data",
            emptyTable: "* no data found",
            info: "Show _START_ - _END_ from _TOTAL_ record",
            processing: "<i class='fa fa-spinner fa-spin'></i> reload data...",
            search: "Search data : ",
            zeroRecords: "0 data found",
        },
        columns: [],
    });

Explanation:

  • paging: used to display pagination.
  • lengthChange: used to indicate the number of rows of data.
  • searching: used to display the data search box.
  • ordering: used to sort data in each column header.
  • info: used to display information on the amount of data.
  • pageLength: the default line length value.
  • createdRow: This callback is executed when the TR element is created. I often use it to add classes to the TR element.
  • fnDrawCallback: This function is called on every ‘draw’ event.

Apart from the options above, the “column” option in datatables also has several options that are often used. As an example

1
2
3
4
5
6
7
8
9
10
11
12
columns: [
      {
        data: null,
        title : "Column names",
        class : "text-right",
        searchable : false,
        orderable : false,
        render: function (data, type, full, meta) {
          return meta.row + 1;
        },
      }
]

Explanation:

  • data: contains the name of the data object key.
  • title: change the column names.
  • class: adds the class name to the column / TD element.
  • searchable: Enable or disable searching for data in this individual column.
  • orderable: Enable or disable ordering data in this column.
  • render: To render data, if you want to display different data or add HTML elements such as button elements (For more details, please try the application demo / datatable example at the end of the article).

4. Retrieve all data in datatables via table rows selection.

If we’re building a CRUD application, it’s a useful technique for getting all the data in the Datatables table row. To get all the data objects on the table row, use the following command.

1
2
3
4
5
6
7
8
9
$(document).on("click", ".btn-edit", function () {
  let current_row = $(this).parents("tr");
  if (current_row.hasClass("child")) {
    current_row = current_row.prev();
  }
  let table = $("#table-data").DataTable();
  let data = table.row(current_row).data();
  console.log("data row" , data);
});

You will get all the data objects in the row selection even though the data is not shown in the table layout.

Get Data Object In Datatable From Row Selection Min

Check out the following demo for a better understanding of this method.

Datatable Examples Demo

Conclusion

Datatables is a mandatory plugin for JQuery programmers. Proper use makes the application smoother and faster. Datatables are also often used to build point of sales systems.

Unfortunately, the official Datatables plugin is not yet available in other Javascript frameworks such as angular and Reactjs. But ReactJs already has an excellent table processing plugin, namely react-table, which is relatively easy to use, and I have discussed it in the tutorial using react-table and reactstrap article.

Thus my article about proficient using Datatables for beginners hope it helps.

Another Javascript Related Post :

  • Tutorial Create Simple POS Using ReactJS And Laravel Lumen Part 1
  • The Using Of Reactstrap And React-Table, Suitable For Beginners
  • Tutorial Create Simple Block UI Using React JS
  • How To Implement Login Page And Protected Route ReactJS
  • Complete Tutorial React Router Dom For Beginners (Easy-To-Understand)
  • The Right Way Understanding React Lifecycle For Beginners

Avatar for Sigit Prasetya Nugroho

About Sigit Prasetya Nugroho

This site is a personal Blog of Sigit Prasetya Nugroho, a Desktop developer and freelance web developer working in PHP, MySQL, WordPress.

Reader Interactions

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Time limit is exhausted. Please reload CAPTCHA.

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Primary Sidebar

Welcome to my Home,

Avatar for Sigit Prasetya NugrohoThis site is a personal Blog of Sigit Prasetya Nugroho, a Desktop developer and freelance web developer working in PHP, MySQL, WordPress.



Popular Articles

Checked checkbox AdminLTE Bootstrap in Jquery

November 4, 2014 By Sigit Prasetya Nugroho 7 Comments

Simple create date format validation with jqueryUI

December 21, 2014 By Sigit Prasetya Nugroho Leave a Comment

Create Simple Progress Bar for Fake Online Generator with Jquery

January 10, 2015 By Sigit Prasetya Nugroho Leave a Comment

22+ Coolest Free Jquery Plugin For Premium Theme

October 3, 2015 By Sigit Prasetya Nugroho Leave a Comment

Easy Build Your Anti Copy Paste Plugin

October 6, 2015 By Sigit Prasetya Nugroho Leave a Comment

Popular Tags

adminlte (15) adsense (13) adsense tips (4) affiliate amazon (13) amazon (12) Android (8) angular (16) angular 4 (12) angular 5 (4) asin grabber (3) Bootstrap (27) codeigniter (5) create wordpress theme (5) crud (8) css (6) free wordpress theme (7) google adsense (4) imacros (4) increase traffic (6) jquery (34) laravel (10) laravel 5 (5) learn android (5) lumen api (4) modal dialog (5) mysql (6) nodeJs (4) optimize seo (4) pdo (6) php (30) plugin (53) pos (8) Publisher Tips (5) react (4) Reactjs (7) SEO (37) theme (17) tutorial angular (5) tutorial angular 4 (6) tutorial javascript (10) tutorial javascript beginners (4) twitter (3) wordpress (18) wordpress plugin (13) XMLRPC (5)




  • About
  • Contact Us
  • Disclaimer
  • Privacy Policy
  • Terms and Conditions

©2021 Seegatesite.com