Javascript datatables do not allow for setting a default column sort

I am encountering an issue where I need to sort the results by a specific column on page load. In this case, I want the initial results to be displayed in descending order based on "RecordDate".

However, it seems that the server side is blocking any sort specification, and any modification I have made below does not load the results properly (e.g., using asSorting [[number of column, and tried name, desc]] etc).

I was wondering if there is a special function I can write here to force the sorting of this column. Is it possible to handle this without modifying a stored procedure or another cs file?

function GetRecords( DTO ) {
var grpid = ApplyGroupingOnTable();
console.log( grpid );
oTable = $( "#SearchTable" ).dataTable( {
    "oLanguage": {
        "sZeroRecords": "No records to display"//,
        //"sSearch": "Search on UserName"
    },
    "aLengthMenu": [[10, 25, 50, 100, 150, 250, 500], [10, 25, 50, 100, 150, 250, 500]],
    "iDisplayLength": 10,
    "sScrollX": "1300px",
    "bSortClasses": false,
    "bStateSave": false,
    "bFilter": false,
    "bLengthChange": true,
    "bPaginate": true,
    "bAutoWidth": false,
    "bProcessing": false,
    "bServerSide": true,
    "bDestroy": true,
    "sAjaxSource": "/Data/SearchRecords",
    "aoColumns": [
        { "mData": "SelectID", "sClass": "alternatingCenterAlign", fnRender: CreateSelectCaseViewerButton, "bSortable": false, "bSearchable": false, "sWidth": "18px" },
        { "mData": "ViewID", "sClass": "alternatingCenterAlign", fnRender: CreateCaseViewerButton, "bSortable": false, "bSearchable": false, "sWidth": "18px" },
        { "mData": "TagID", "sClass": "alternatingCenterAlign", fnRender: CreateTagCaseButton, "bSortable": false, "bSearchable": false, "sWidth": "18px" },
        { "mData": "ID", "sClass": "alternating", "sType": "string", "bSortable": true, "bSearchable": false, "sWidth": "50px" },
        { "mData": "ClientName", "sClass": "alternating", "sType": "string", "bSortable": true, "sWidth": "120px" },
        { "mData": "RecordDate", "sClass": "alternating", "sType": "string", "bSortable": true, "bSearchable": false, "sWidth": "70px" },

    "bJQueryUI": false,
    "sPaginationType": "full_numbers",
    "bDeferRender": true,
    "bRetrieve": false,
    "fnServerParams": function ( aoData ) {
        aoData.push( { "name": "iParticipant", "value": $( "#participant" ).val() } );
        aoData.push( { "name": "iSearch", "value": JSON.stringify( DTO ) } );
        aoData.push( { "name": "iId", "value": cliid } );
        aoData.push( { "name": "iOrder", "value": grpid } );
    },
    "fnDrawCallback": function ( oSettings ) {
        if ( grpid ) FinalGrouping( oSettings, grpid );
        $( ".overflow" ).each( function () { $( this ).attr( 'title', $( this ).text() ); } );
        $( '#tablediv select' ).chosen();
    },
    "fnServerData": function ( sSource, aoData, fnCallback ) {
        $( '.grid-loading' ).show();
        $.ajax( {
            dataType: 'json',
            contentType: "application/json; charset=utf-8",
            type: "GET",
            url: sSource,
            data: aoData,
            cache: false,
            success: function ( msg ) {
                if ( msg.Exception != undefined ) {
                    alert( msg.Exception );
                    $( '.grid-loading' ).hide();
                    return false;
                }
                lastId = ( msg.aaData.length > 0 ) ? msg.aaData[msg.aaData.length - 1][0] : 0;
                fnCallback( msg );
                $( '.grid-loading' ).hide();
            }
        } ); //End Ajax Call
    }
} );
}

Answer №1

If you have the ability to obtain the data array of the dataTable in the format shown below:

var data = [
               { "title": "some title", "value": 123 },
               { "title": "another title", "value": 456 }
           ];

You can easily perform a descending sort based on the "value" using the code snippet provided:

data.sort(descendingSortOnValue);

The following function definition is required:

function descendingSortOnValue(a, b) {
        var aValue = Array.isArray(a.value) ? Math.max(...a.map(obj => obj.value)) : a.value;
        var bValue = Array.isArray(b.value) ? Math.max(...b.map(obj => obj.value)) : b.value;

        if (aValue > bValue)
            return -1;
        if (aValue < bValue)
            return 1;
        return 0;
    }

I'm not sure if this information will be useful to you. Although I haven't personally used the dataTable library, it seems interesting and logical that you should be able to access the data stored in arrays after retrieving it from the server.

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

What is the process for using Discriminators, the Mongo DB API, and Mongoose to insert data into Cosmos DB?

Issue Overview I am currently facing a challenge in writing documents to my Cosmos DB using the Mongo DB API and Mongoose for Object Modeling. To optimize costs, I aim to store all documents in a single collection by utilizing Discriminators. The project ...

What's causing the zero to appear after the ajax call?

This is my first time learning Ajax with WordPress and I'm trying to implement Ajax functionality with a widget. However, I am encountering an issue where I get a 0 after the form is submitted. Can someone provide guidance and explain why this is hap ...

Utilizing the jQuery library for flexible REST API requests with the incorporation

I'm currently utilizing jQuery getJSON to fetch posts from the WP API v2. There are some input fields that I'd like to make clickable, and then add extra parameters to the request URL. Here are some example requests: Posts - https://www.example ...

How can I transfer a selected value from a unique dropdown component to react-hook-form?

I am utilizing react-hook-form for form validation in this Gatsby project. However, my dropdown component is not a <select> tag but a customized component created with divs and an unordered list. This design choice was made to meet our specific custo ...

What is the process for exporting/importing a variable in Node.js?

What is the correct way to export/import a variable in Node.js? I attempted to use export and import methods, but I received an error message stating that it should be a module. After changing the type to module in the JSON file, it then told me that requ ...

What is the process for using AJAX and PHP to upload an image file?

I'm facing an issue where I want to insert an uploaded image into a database with user details for a profile picture. The output I receive currently shows {"current_field":null,"field_count":null,"lengths":null,"num_rows":null,"type":null}. How can th ...

Manipulating child classes using jQuery

I am struggling to display an X icon next to a tab on my page when the tab is clicked, but I am facing difficulties in toggling its visibility. The issue arises when trying to access the span element within the tabs. $('.tabs .tab-links a').on(& ...

Is there a way to use Node.js to automatically redirect any random string paths back to the main home page?

Is there a way to configure my basic Node.js server to use simple paths instead of query strings for user session IDs? For instance, can I make domain.com/GH34DG2 function the same as domain.com within my web app? This format seems more visually appealing ...

Why is it necessary in JavaScript to reset the function's prototype after resetting the function prototype constructor as well?

Code is often written in the following manner: function G() {}; var item = {...} G.prototype = item; G.prototype.constructor = G // What is the purpose of this line? Why do we need to include G.prototype = item before resetting the prototype? What exact ...

What is the simplest method to create a scroller for engaging narratives?

I am in the process of creating a static but responsive storytelling website using HTML. My objective is to create an effect similar to this: https://i.stack.imgur.com/zIEpU.gif The idea is to have text on the left and a *.jpg image fixed on the right. As ...

Issue with MVC 4 Asynchronous File Upload: Controller Always Receiving Null Value

I'm encountering an issue while attempting to upload a file asynchronously from ajax to my controller. I am passing 3 variables - PictureId, PictureName, and PictureFile. The problem specifically lies with the "PictureFile" variable as it consistently ...

Load options from server directory using PHP jQuery AJAX

I am faced with a file structure on my server that resembles the following: My query is quite complex: How can I dynamically populate <select> HTML tags from the contents of sub-files on a server? For instance, I have 3 <select> tags here tha ...

Sending data using Ajax to the server-side code in ASP.NET

Struggling to successfully pass a series of values through Ajax to a code-behind method in order to insert the data into a database table. However, encountering issues where string variables are being received as empty strings and int variables as 0. The ...

What could be causing this test to fail when testing my API endpoint?

Why am I encountering this error? Uncaught exception: Error: listen EADDRINUSE: address already in use :::3000 import supertest from "supertest" import axios from "axios" import app from ".." const request = supertest(app ...

Select a particular item and transfer its unique identifier to a different web page. Are there more efficient methods to accomplish this task without relying on href links and using the $_GET

Could there be a more efficient method for transferring the ID of a specific motorcycle from index.php to inventory.php when it is clicked on, aside from using href and $_GET? Perhaps utilizing hidden fields or submitting a form through JavaScript? What ...

Send the data from a table to a Python method in Flask using AJAX

Recently, I picked up on flask and decided to create a small web tool for organizing data. The main page displays a table of list numbers and their respective descriptions. I managed to implement jQuery functionality that allows double clicking to select i ...

Transferring cookies across subdomains

I am facing an issue with an ajax request going from one subdomain to another, for example from sub1.example.com to sub2.example.com. Despite having a cookie set for all domains (cookie domain='.example.com'), the cookie is not being sent to the ...

Ruby on Rails allows for the selection of values in a dropdown menu to trigger the visibility of different sections of HTML

As a newcomer to Rails, I was able to successfully implement the onclick function for a f.checkbox element. Now, my challenge lies in achieving a similar functionality for a f.select element within a _form. Below is the code snippet that works for a chec ...

Despite providing the correct token with Bearer, Vue 3 is still experiencing authorization issues

I am working on a project that involves Vue 3 with a Node Express back-end server and Firebase integration. On the backend server, I have implemented the following middleware: const getAuthToken = (req, _, next) => { if ( req.headers.authori ...

Discover the Secrets of Securing User Authentication in AJAX-based WCF Service Calls

I am currently working on a WCF service that requires client-side (ajax) calls. I am considering two options: either using ScriptManager on the ASPX page to add a ServiceReference to the WCF service, or making JQuery ajax calls directly to the WCF servic ...