The selected rows in Datatables.js do not retain their selection status after calling ajax.reload()

As per the information provided on the Datatables website, the feature "retain row selection over a data reload" should work seamlessly. However, I am facing issues with it when using data from an ajax source.

Below is the code snippet showcasing how I am creating my table:

  oTable = $('#fileList').DataTable({
    select: true,
    "ajax": {
      "url": "./data.php",
      "type": "GET"
    },
    rowId: 'Index',
    "createdRow": function (row, data, dataIndex) {
      $(row).addClass(data[2]); //set formatting from data[2]
    }
  });

Following the guide from the reference mentioned above, initially I tried refreshing the table every five seconds with the following code:

setInterval(function () {
    oTable.ajax.reload();
}

However, the issue persisted where any selected row would get deselected every five seconds. To address this, I attempted a more explicit approach by saving the selected rows into an array and re-selecting them inside the setInterval function:

setInterval(function () {
    var selectedRows = [];
    // Store all selected rows in an array:
    sel = oTable.rows('.selected').every(function (rowIdx) {
      selectedRows.push(rowIdx);
    });
    oTable.ajax.reload();
    console.log(selectedRows);
    // Re-select all rows from the array
    for (var i = 0; i < selectedRows.length; i++) {
      console.log("selecting ",selectedRows[i]);
      oTable.rows(selectedRows[i]).select();
    }
  }, 5000)
});

When checking the Console, I noticed that a selected row (in this case, the third row) was correctly captured in the array:

Array [ 2 ]
selecting  2    

However, the rows were not getting re-selected. Manually selecting the row using oTable.rows(2).select(); in the console worked fine but not within the setInterval block.

I suspect that the issue might be related to the rowID property. This is how I defined the table structure in the HTML:

      <table id="fileList" class="display">
        <thead>
          <tr>
            <th>Index</th>
            <th>Status</th>
            <th>Owner</th>
          </tr>
        </thead>
      </table>

The data is fetched from a PHP script which returns an array like:

{"data":[["1", "foo", "bar"], ["2", "fuz", "baz"]}

where the first item represents the index.

Answer №1

The issue at hand appears to stem from the absence of keys within the data being returned. Have you experimented with returning the data in the form of an associative array, resembling the following:

"data": [
    {
        "category": 1,
        "type": "Example",
        "author": "Sample"
    }
]

You could then consider substituting:

ID: 'Category',

with:

ID: 'category',

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

Trouble with visibility of Angular controller variables on scope

I recently adjusted my code to align with John Papa's Angular style guide, but encountered an issue where my controller is no longer visible in ng-inspector. If I can successfully display vm.message, I believe I can resolve the remaining issues (thoug ...

Using ng-disabled on input elements within an ng-repeat directive

Showing different inputs based on an array looks like this <div data-ng-repeat="n in langInput.values"> <input type="text" id="auction_name_{{n.selected}}" class="form-control" name="auction_name_{{$index}}" ...

Prevent the use of unnecessary object properties

Currently, my project involves using Typescript and React in conjunction with Material-UI. Specifically, I am utilizing Material-UI's styling solution, which implements CSS in JS methodology in a Hook-like manner as outlined in their documentation: co ...

Diminish, then lead to a fresh page

I have encountered an issue with my code. The wrapper performs a fade out effect before redirecting the user to a URL. However, it only fades out once and I suspect this is due to the browser caching or loading the page quickly. Is there a way to ensure t ...

restart form upon div closure via ajax

Is there a way to revert my form back to its original state upon closing a div? I'm currently utilizing ajax and django. A suggestion I received was to include a reset_recipe field in my form that, when set to true, resets the recipe. Below is my d ...

Combining two arrays with varying lengths based on their values

Seeking assistance with a programming task that is straightforward yet challenging for me. There are two arrays: one long and one short. var arrayShort = [ { id: 'A', name: 'first' },{ id: 'B', name: &ap ...

What is the most effective way to enlarge an HTML table in the center?

Currently, I am dynamically generating an HTML table using a repeater. The table consists of four columns that I populate with company data. My goal is to enable users to click on a row and have another row appear below it, containing a Google map and addi ...

Troubleshooting HMR issue in webpack 4 for ReactJS: HTML and SCSS not refreshing

Currently, I am setting up webpack for my application and in development mode, I would like to enable HMR (Hot Module Replacement) that automatically refreshes the page whenever there are changes in HTML, SCSS, and JSX files. The entry point for my project ...

Removing an item from a JSON array based on its value using jQuery

This is a section of my JSON array: var videos = $j.parseJSON(' [ { "privacy":"public", "id":"1169341693" }, { "privacy":"private", "id":"803641223" }, { "privacy":"public", "id":"1300612600" }, ...... When I use co ...

The tools needed for securing a web application with ExpressJS include the use of

I recently implemented an upload function using connect-form with formidable and https://github.com/ctavan/express-validator. While attempting to sanitize an image from XSS, I encountered a 'TypeError: Cannot call method 'replace' of undefin ...

What is the appropriate response to send to the user in a web application?

I am currently developing a web application that utilizes AngularJS for the frontend, a REST API, and MongoDB as the backend, all powered by Node.js. Background to the challenge: One key requirement is to authenticate users using token-based authenticati ...

Determine the value of an array element based on a specified

I am in the process of creating an array, currently consisting of a single object that is computed based on other objects from a JSON file. Sampling my code // Retrieve JSON data and convert it to an object let myFile = '{"foo": {"bar": "baz"}, "thu ...

Insert an HTML page into a div element

I am having an issue with my angular template. I have a div where I am attempting to load an HTML view file (.html) based on a $watch event, but for some reason, the HTML view is not being loaded into the div. Below is a snippet of my controller code that ...

Include a new feature within an onClick event

I'm looking to implement a single page application using React.js and I want to incorporate a list within a material-ui drawer. The goal is to dynamically add elements to an array every time a button is clicked, but I'm stuck on how to write this ...

The issue arises where a string is detected instead of a boolean value in the schema when generating a list using the

Embarking on my journey as a Mailchimp application developer, I encountered an issue while attempting to create a list through the Mailchimp API. Has anyone else experienced this error? Below is the HTML code I used for the checkbox input: <input id ...

Add a variable from a callback function in AJAX's success response

Is there a way to effectively utilize the variable in the appended message of the AJAX success call? http://codepen.io/anon/pen/fdBvn data['name'] = $('#goofy').val(); $.ajax({ url: '/api/1/email/test/', data: data, type ...

Tips for simulating the $timeout service with sinon?

I am looking to write a unit test for a method within an Angular controller that uses the $timeout service. However, I have been advised not to use inject in this scenario. Therefore, I need to mock $timeout on my own. Can someone guide me on how I can a ...

ESLint has detected an unexpected use of an underscore in the variable name "__place". Avoid using dangling underscores in variable names to follow best coding practices

I received the JSON response shown below. To validate the _place, I used responseData.search[0].edges[0].node._place { "data": { "search": [ { "_place": "SearchResultItemConnection", "edges": [ { "cursor": ...

Trouble arises when attempting to bind a JavaScript event with an innerHTML DOM element

I am currently dealing with a complex issue on how to bind a JavaScript event to an innerHTML DOM element. The scenario involves having a div with an input checkbox inside it, along with some pre-existing JavaScript event bound to that checkbox. Additional ...

What sets defineProps<{({})}>() apart from defineProps({ }) syntax?

While examining some code written by another developer, I came across the syntax defineProps<({})>(). After doing some research, I couldn't find any resources that helped me understand this particular syntax. My Way of Defining Props defineProp ...