The search and pagination features of Bootstrap dataTable do not function properly when the data is being retrieved from an AJAX API response

Currently, I am in the process of developing an admin panel. While I have successfully loaded data from an Ajax API response into a bootstrap dataTable, I have encountered issues with the default search and pagination functionalities of the table.

"processing": true,
"serverSide": true

I attempted to initialize the table by using the above code snippet, but unfortunately, it did not rectify the problem.

My question is whether it is possible for the dataTable functionality to work as expected, following the defaults provided by Bootstrap dataTable.

In order to achieve this, I intend to undertake the following steps:

Step1: Create a form with a submit button.

Step2: Upon clicking the submit button, trigger an ajax call to retrieve JSON Data dynamically and populate the dataTable rows.

Step3:

$("#editable-sample").DataTable({ // what should I do here.});

Problem

The issue currently faced is that although the data is loading onto the page, the search box and pagination features are non-functional.

Answer №1

Could you please provide the code you are working with?

Have you double-checked that your table meets all of the necessary prerequisites for dataTables to function properly? Here are a few key requirements:

  1. Your table should contain both <thead> and <tbody> tags
  2. Make sure your table has an id attribute that matches the one used in the sample launch script:

    <table class="table table-bordered" id="dataTables-example">
     <script>
       $(document).ready(function() {
           $('#dataTables-example').dataTable();
       });
    </script>

Answer №2

datatables offers support for Ajax data sources in the form of objects, click here to learn more

Here is an example extracted from the official documentation of DataTables:

JS

$(document).ready(function() {
    $('#example').DataTable( {
        "ajax": "data/objects.txt", //
        "columns": [
            { "data": "name" },
            { "data": "position" },
            { "data": "office" },
            { "data": "extn" },
            { "data": "start_date" },
            { "data": "salary" }
        ]
    } );
} );

HTML

<table id="example" class="display" cellspacing="0" width="100%">
        <thead>
            <tr>
                <th>Name</th>
                <th>Position</th>
                <th>Office</th>
                <th>Extn.</th>
                <th>Start date</th>
                <th>Salary</th>
            </tr>
        </thead>

        <tfoot>
            <tr>
                <th>Name</th>
                <th>Position</th>
                <th>Office</th>
                <th>Extn.</th>
                <th>Start date</th>
                <th>Salary</th>
            </tr>
        </tfoot>
    </table>

AJAX

{
  "data": [
    {
      "name": "Tiger Nixon",
      "position": "System Architect",
      "salary": "$320,800",
      "start_date": "2011/04/25",
      "office": "Edinburgh",
      "extn": "5421"
    },
    {
      "name": "Donna Snider",
      "position": "Customer Support",
      "salary": "$112,000",
      "start_date": "2011/01/25",
      "office": "New York",
      "extn": "4226"
    }
  ]
}

Answer №3

$.ajax({..

 success: function(data) {..  

var table = $('#datatable').DataTable();
table.clear().draw();
var rowNode= new Array();
for (var key=0, size=data.length; key<size; key++){
            var j = -1;
            var r = new Array();
// storing data columns in an array
                r[++j] ='<tr><td><input type="hidden" name="somename1" value="'+data[key].id+'"/><input type="hidden" name="somename2" value="'+data[key].is_deleted+'"/>'+data[key].lic_category_name+'</td>';
                r[++j] = '<td>'+data[key].someval1+'</td>';
                r[++j] = '<td>'+ data[key].someval2+'</td>';
                r[++j] = '<td>'+ data[key].someval13+ '</td>';
                r[++j] ='<td class="last"><a href="view?id='+data[key].id+' title="View"><i class="fa fa-eye"></i></a> <a href="edit?id='+data[key].id+'title="Edit"><i class="fa fa-edit"></i></a> <a href="delete?id='+data[key].id+'onclick="return confirm("Are you sure you want to delete?")" title="Delete"><i class="fa fa-trash"></i></a></td></tr>'; 
                rowNode = table.row.add(r);

        }

        rowNode.draw().node()

   }
}

This is my JSON Response,

[{"id":70,"somekey1":"GC 1","somekey2":"GC 1","somekey3":8,"somekey4":5000,"somekey5":1,"somekey5":1,"is_deleted":0}]

The code worked successfully for my specific needs.

Answer №4

The issue arose due to a conflict with the 'column' attribute attempting to match data row values with the column before retrieving the data.
So I decided to place the closing Curly bracket of the 'ajax' attribute before the 'column' attribute.
Now, the column attribute function will only be called after the ajax function is complete.

$(document).ready(function() {             
    $('#example').DataTable( {            
        "ajax":{ "data/objects.txt" },//<------------------------------------------------place here//            
        "columns": [                                                              
            { "data": "name" },             
            { "data": "position" },         
            { "data": "office" },        
            { "data": "extn" },           
            { "data": "start_date" },          
            { "data": "salary" }         
        ]          
    });  
} );

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How to access an element through the router-outlet in Angular 6?

<side-navigation [navigationTitle]="navTitle"></side-navigation> <router-outlet> </router-outlet> Within my project, I have a navigation bar located in the root component. I have set up [navigationTitle] as an @Input Decorator wit ...

Retrieving saved data from LocalStorage upon page reload

<div ng-repeat="section in filterSections"> <h4>{{ section.title }}</h4> <div class="checkbox" ng-click="loaderStart()" ng-if="section.control == 'checkbox'" ng-repeat="option in section.options"> <label ...

I'm facing an issue where my React onClick event is not functioning as expected; whenever I click,

When I click the create button, my page is not refreshing and the required part is not working. If I try not using onClick onSubmit, the required part works, but when I click the button, the page refreshes. I'm not sure why. I have written e.preventDe ...

What is the best way to handle code versioning using Django, Angular2, and Webpack?

Currently, I am utilizing Django in conjunction with Angular 2 and Webpack. Within Django, I have set up a URL to display my application at http://example.com/user/beta. Initially, my index.html file is rendered, which contains my Angular 2 components. Wit ...

Prepare the data for parsing into a highcharts pie chart

I developed an application that retrieves JSON data of the top stock movers in a day from a Google spreadsheet. Using this data, I create a pie chart displaying the various movers and the number of shares sold by populating the chart through AJAX. Below i ...

What is the method for acquiring a dynamic segment in the router of a Next.js 13 application?

Currently in my project, I am using the new App Router in Next.js 13 and MongoDB as the DBMS to fetch data via API. When trying to retrieve all data from a collection, it is successful. However, fetching only one data results in failure. The error message ...

How can Vue.js pass an array from a child component to its parent component?

I'm currently developing a contact book app and I have created a modal within a child component that contains a form with several input fields. My goal is to utilize the values entered in the form and add them to the parent component. I have successfu ...

Understanding the process of sending data from a Cordova application to a PHP script and storing it in

I'm a beginner in cordova app development and I have a question about posting data from a form in a cordova application using PHP and MongoDB. I have my index.html file in the cordova app and comment.php in c:/xampp/htdocs. I want to display data from ...

Show or hide the sibling element of the current element without using a specific identifier in jQuery

I am looking to make div.edit-button toggle its corresponding sibling div.additionalFieldForm. There are multiple instances of both on the page, so I want to target only the pair that are related within the same group. If a div.edit-button is clicked, the ...

Initiate an Ajax request solely for the elements currently visible on the screen

I am currently facing an issue that requires a solution. Within our template, there are multiple divs generated with the same classes. Each div contains a hidden input field with the ID of the linked target site. My task is to utilize this ID to make aja ...

Tips for properly modifying an attribute within an array of objects in JavaScript using ReactJS

My array of objects looks like this: this.state = { itemSquare: [{ item: "bomb", status: false }, { item: "bomb", status: false }, { item: "bomb", status: false }, { item: "bomb", status: ...

React, incorporating emojis within a dropdown menu

Recently, I've been developing a small game using React where players can customize settings before beginning. The game involves four players chasing different tokens on the map while avoiding the player designated as "it". Within my code, I have a r ...

Using browserify "require" in console: A step-by-step guide

My Rails project now includes the browserify and pinyin packages, thanks to the browserify-rails installation. To find out more about the pinyin package, check out this link: https://github.com/hotoo/pinyin var pinyin = require("pinyin"); console.log(pin ...

Blend express router by chaining the (.route) method with other HTTP methods like (.get, .post, etc) to create

Here is my code structure: let router = require( 'express' ).Router(); Later on, I define my routes like this: router .route( '/' ) .get( listMiddleware ); router .route( '/:id' ) .get( getOneByIdMiddleware ...

TS type defined by JS constants

I am currently working on a project that involves both JavaScript and TypeScript. I am trying to find a solution to reduce code duplication when using JavaScript string constants by converting them into TypeScript types. For example, let's say I have ...

What is a common mistake when using refs in React?

I've recently started diving into React. I've seen conflicting opinions on using refs - some sources claim it's a bad practice altogether. Can someone clarify this for me? Is it harmful to attach refs to child components in order to access ...

What is the best way to use command line arguments within a Node.js script?

As a newcomer to the world of programming, I find myself struggling to make progress despite putting in significant effort. Although it may seem like a trivial question, my lack of progress is becoming frustrating. Currently, I am working on a node.js scr ...

The function is missing from the object, leading to a script error with jQuery

When using different versions of jQuery, I encountered some issues with saving changes in my application. Initially, with jquery-1.4.4.min.js, everything worked except for the save function due to an error I made. However, when switching to jquery-1.7.1.mi ...

Tips for maintaining consistent header and footer while developing the front end using JavaScript

Is it possible to maintain the same header and footer on all pages of a website if using JavaScript for the front end and PHP for the back end? While I am comfortable doing this with PHP, I am curious if it can also be achieved with JavaScript or HTML, o ...

Plane is constantly cloaked in darkness

I'm having trouble adding a texture to my plane that repeats both horizontally and vertically. Every time I try to apply the texture, it shows up as black. I've attempted to add some lights to the scene, but the issue persists without any errors. ...