Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

209
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda