Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

208
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda