Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

207
Views
Use JavaScript DataTable with getCookie and SetCookie

I want to remove the hard-coded values from "order" and get those values from "getCookie" function. How can I do this? Whenever I click on a table column, it gets sorted. I want to store that sorting order by setCookie function. When the page refreshes, I want to get that sorting order from getCookie function. Thanks.

  $(document).ready(function () {
        let sortValue = getCookie("releaseTicketSort")
        var oTable = $('#allTicketsTable').DataTable({
            "pageLength": 5,
            "lengthChange": true,
            "fixedHeader": true,
            "lengthMenu": [ [5, 10, 25, 50, -1], [5, 10, 25, 50, "All"] ],
            "order": [[2, 'asc']],

            columnDefs: [
                { width: 150, targets: 5 },
                { className: "dt-center", targets: 5}
            ],

            fnDrawCallback: function (settings){
                console.log(settings.oSavedState.order)
                var orderVec = settings.oSavedState.order
                setCookie("releaseTicketSort", orderVec, exp=1000)
                getCookie("releaseTicketSort")
            }
        });
    });

function setCookie(c_name,value,exdays) {
    var exdate=new Date();
    exdate.setDate(exdate.getDate() + exdays);
    var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());
    document.cookie=c_name + "=" + c_value;
}

function getCookie(c_name) {
    var i,x,y,ARRcookies=document.cookie.split(";");
    for (i=0;i<ARRcookies.length;i++) {
        x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
        y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
        x=x.replace(/^\s+|\s+$/g,"");
        if (x==c_name) return unescape(y);
    }
}
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Instead of using cookies, I would suggest using the state-saving functions built into DataTables (assuming you are using DataTables v1.10 or later).

For your scenario where you only want to save the state of sorting between page loads (but not paging, and not filtering), then the stateSaveParams option is probably the simplest approach:

$(document).ready(function() {

  var table = $('#example').DataTable( {
  
    stateSave: true,
    
    stateSaveParams: function (settings, data) {
      data.start = 0;
      data.search.search = '';
    }

  } );
  
} );

The above options cause all the table's state data to be stored in your browser's local storage. A typical entry will contain data in the following structure:

{
    "time": 1651180700425,
    "start": 0,
    "length": 10,
    "order": [
        [0, "asc"]
    ],
    "search": {
        "search": "",
        "smart": true,
        "regex": false,
        "caseInsensitive": true
    },
    "columns": [{
        "visible": true,
        "search": {
            "search": "",
            "smart": true,
            "regex": false,
            "caseInsensitive": true
        }
    }, 
        . . . 
    {
        "visible": true,
        "search": {
            "search": "",
            "smart": true,
            "regex": false,
            "caseInsensitive": true
        }
    }]
}

The stateSaveParams option will then override the start and search.search values so those are saved as their default values (first page, and no search term) instead of whatever values the user may have provided:

stateSaveParams: function (settings, data) {
  data.start = 0;
  data.search.search = '';
}

Nothing else is altered - including the sorting values. This saved data is automatically retrieved from local storage by DataTables, because of the stateSave: true option.

So, you don't need to explicitly save the sorting data - you only need to explicitly "unsave" the other options that you don't actually want to preserve/restore.

Background and reference: More about local storage.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!