DisplayStart in DataTables for dynamic data presentation

I'm currently working on a JavaScript function that needs to utilize a dynamic value for "displayStart". The data is being retrieved from a PHP script in JSON format. Below is the snippet of my JavaScript code:

    balance.list = function () {
    $('#balance').dataTable({
        processing: true,
        ajax: {
            url: 'php/list.php',
            dataSrc: 'data'
        },
        dom: '<"top"flp<"clear">>rt<"bottom"ip<"clear">>',
        pageLength: 50,
        autoWidth: false,
        displayStart: '100',

        columns: [
        {
            width: "10%",
            data: "date"
        }, {
            width: "5%",
            data: "checknum"
        }, {
            width: "75%",
            data: "description"
        }, {
            width: "5%",
            data: "debit"
        }, {
            width: "5%",
            data: "credit"
        }, {
            width: "5%",
            data: "balance"
        }]
    });
};

Instead of displayStart: '100', I would like it to be something like: displayStart: displayStart.displayStart,

However, I have set the data source to 'data', which is another branch within the JSON structure.

Here is the structure of the JSON data:

{
  "displayStart":"100",
  "data": [
  {
    "date":"2015-03-27",
    "checknum":null,
    "description":null,
    "debit":"50.00",
    "credit":"0.00",
    "balance":"500.00"
  },
  {
    "date":"2015-03-28",
    "checknum":null,
    "description":null,
    "debit":"0.00",
    "credit":"250.00",
    "balance":"750.00"
  }
  ]
}

I have experimented with the ajax part using success/error functions, but it interrupts the completion of the table generation.

How can I effectively update the value?

Answer №1

If you want to dynamically change the page after loading data in DataTables, you can achieve this by incorporating two event handlers following your DataTables initialization code. The code snippet below demonstrates how to implement this:

// Triggered when an AJAX request in DataTables completes
$('#balance').on('xhr.dt', function( e, settings, json){
   $(this).data('is-loaded', true);
});

// Triggered when the DataTables table is redrawn
$('#balance').on('draw.dt', function (){
   if($(this).data('is-loaded')){
      $(this).data('is-loaded', false);
      var api = $(this).DataTable();
      var json = api.ajax.json();
      var page_start = json['displayStart'];

      // Determine the current page number
      var page = Math.min(Math.max(0, Math.round(page_start / api.page.len())), api.page.info().pages );

      // Update the page
      api.page(page).draw(false);
   }
});

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

The disappearance of the "Event" Twitter Widget in the HTML inspector occurs when customized styles are applied

Currently, I am customizing the default Twitter widget that can be embedded on a website. While successfully injecting styles and making it work perfectly, I recently discovered that after injecting my styles, clicking on a Tweet no longer opens it in a ne ...

Failure of html and javascript banner in Adobe AIR application

Here's a simple breakdown of the Adobe AIR application setup. The main window of the application is an HTML file, and the `application.xml` file looks like this: <initialWindow> <title>window title</title> <content>i ...

Please input two words in the textbox using AngularJS

I am currently facing a challenge that requires me to make the user input both their first and last name into a single text box. I am using AngularJS for this task, and my goal is to validate the text field using ng-pattern. The requirement is that the fie ...

Match one instance of a character in a regular expression pattern while simultaneously matching two occurrences of a different character

I am attempting to create a function that can match one occurrence of a certain character and two occurrences of another character simultaneously. For instance, in the string "_Hell_o", I want to match the first underscore (_) and in the string "++Hello", ...

How to parse JSON data (coming from a Socket.io response) in Unity

When I retrieve data from the web server in json format, I am unable to deserialize it and access the keys (e.g., first_name). The client receives the information, but the code fails to print anything in the Unity console. Here is my code: socket.On("Us ...

Steps for assigning an id to a newly created div within a parent div while in design mode

Imagine creating a div element with the attribute contenteditable="true", and then checking the console for what happens next: 1st. In the console, you only see a simple div tag. <div id="typbody" contenteditable="true" style="width:100%; height:200px ...

Using jQuery to retrieve child elements and assign numerical values to them

Looking for a jQuery function that can apply different CSS attributes to children elements of a div. <div class="container"> <div class="autogenerated-div"></div> <div class="autogenerated-div"></div> <div class="aut ...

Is there a way in Vue.js for me to access a method from within the same component using the component's data?

Below is the code for a specific component: <template> <li v-for="(item, i) in this.menu" :key="i" @click="item.action()"> //attempting to call the method in the component {{menu.title}} <li> </template> <script> ...

Is there a way to manipulate a website's HTML on my local machine using code?

I am currently working on a project to create a program that can scan through a website and censor inappropriate language. While I have been able to manually edit the text using Chrome Dev tools, I am unsure of how to automate this process with code. I ha ...

Tips on transitioning between two tables

Recently, I created an HTML page entirely in French. Now, I am attempting to incorporate a language translation feature on the website that allows users to switch between French and English (represented by two flag icons). My concept involves using a tabl ...

Exploring Hibernate relationships through a RESTful API cycle

The following code snippet represents the database schema: DB: Persons(id, name) Phonenumbers(number, id_persons) FK id_person references Persons(id) Java code: package com.app.model; import javax.persistence.Column; import javax.persistence.Entity; ...

Clickable element to change the display length of various lists

I am working on a project where I have lists of checkboxes as filters. Some of these lists are quite long, so I want to be able to toggle them to either a specified length or the full length for better user experience. I have implemented a solution, but th ...

Encountering difficulties in sending image data to server using Retrofit

Currently, I am facing challenges in sending an image to the server through retrofit. While the server can receive what I send, there seems to be an issue when I test it with Postman, as it displays something unexpected. Let me walk you through my data fir ...

What is the best way to extract a substring separated by two line breaks using a specific index?

Consider having the following string: Apple Banana Pear Pineapple Grapefruit Kiwi Lime Lemon Cherry If I am interested in extracting the line: Pineapple Grapefruit Kiwi how can I achieve this by identifying any index within the second line and locatin ...

Retrieve the image link from a Flickr JSon Feed

I'm currently displaying images from a flickr feed on my webpage. Everything is working well, but when I click on an image, it takes me to the page where the image is hosted. What I want is for the images to link directly to the image itself, not th ...

What is the best way to dynamically adjust the hover color of a bar in a Highchart

The below code is used to set the hover color of the bar: plotOptions: {column: {states: {hover: {color: '#000000'}}}} Is there a way to dynamically change the bar hover color? ...

Tips on passing parameters during the initialization of an angular factory

Imagine a scenario where an Angular factory holds a substantial amount of raw data (referred to as _fakeData), and I aim to reveal a specific portion of the data based on the parameters passed during initialization (known as _exposedData). Currently, I ha ...

Exploring the Power of BufferGeometry and Textures in Three.js

I am experiencing an issue where the texture does not show up when I try to load textures on a THREE.BufferGeometry. However, the texture displays correctly when using normal geometry. Could it be that textures are unsupported with BufferGeometry, or am I ...

Momentjs initially indicates that the date is valid, logs the correct date, and displays the accurate duration using .fromNow(). However, this suddenly switches

I am currently working on converting the createdAt date in my Nuxtjs application that is fetched from MongoDB using an express app, with the help of moment.js. Initially, when I check if the date is valid, it shows as valid but then it switches to an incor ...

Removing a Node in VisJs in Real Time

function activateAddEdgeMode(nodeId){ network.addEdgeMode(); } /**looking to implement a method similar to network.addEdgeMode(); that will allow for node deletion. For instance: network.deleteNodeMode()*/ ...