4 ways to fix – Cannot reinitialize jQuery DataTable

jQuery DataTable is very user-friendly & provides a lot features and is easier to use. But when we use jQuery DataTable, we face a unique type of alert message (Cannot reinitialize JQuery DataTable).

These DataTables show the data in listing at front-end and in an good user friendly manner. It also provides features to use like sorting, searching, paging, and export to different types of file and print.

Cannot reinitialize jQuery DataTable

This is actually a warning message shown by jQuery DataTable. At initial level, an user can not understand this warning. So In consideration of this issue, I am writing this article.

Meaning:

This warning means that we can not initialize a jQuery DataTable more than once and we can not change it’s configuration options after initialization once. If we want to set any option after initialization, then we have to use it’s API Otherwise it will give us this type of warning. Just see this below given code :

Here we are using jQuery Datatable constructor instance 2 times for the same element for setting 2 different options and this will result with the warning.

Some tips, trick and fixes to efficiently use jQuery Colorbox or Fancybox.

4 ways to fix – Cannot reinitialize jQuery DataTable

There are number of ways to resolve this issue. I am listing out four ways to resolve the warning.

1. Single initialisation

We should set jQuery DataTable configuration options by using only one instance. In the case of the above example, we should initialize like this :

2. Object instance retrieval

In this option, we can retrieve the object instance of already initialized jQuery DataTable. In this case we will use $.fn.dataTable.isDataTable() method. This can be used to check if a table is a DataTable or not already.

3. Retrieve the Instance

jQuery DataTable provide this option in it’s configuration. Which provides a short-cut way to explicit check using $.fn.dataTable.isDataTable() as above when obtaining a DataTable instance:

Means using this option, If any old DataTable instance exists then It will retrieve that instance instead of giving error.

4. Destroy existing instance

By destroying existing instance also, we can resolve this issue. This can be done by 2 ways:

There is also a destroy option that can be used to destroy old DataTable

Like this, we can destroy the old table on existence and then create new instance of jQuery DataTable:

These above all are 4 ways to fix warning, Cannot reinitialize jQuery DataTable. If you know other ways to fix the same, don’t miss to comment.

You Might Interested In

Leave a Reply

Enclose a code block like: <pre><code>Your Code Snippet</code></pre>.