Simple paging with Javascript

Asked

Viewed 323 times

0

I made a system to list billets consuming a API, but I need to generate a simple pagination (< Previous Next >) by passing the parameter "lastEvaluated" in the GET. If this parameter exists, it delivers the next batch of records. How could you do this, there is some function that of a shortcut?

Object Array:

{
  "items": [
    {
      "dueValue": 1964.56,
      "boleto": {
        "uri": "https://myurl/31263-7F6C1136-B1EF-40F4-AB5D-E2B969B94E0A.pdf",
        "digits": "99999999999999999999999999999999999999999999999",
        "bank": "Itaú Unibanco S.A."
      },
      "doc": "108506",
      "dueDate": "2021-03-29",
      "payerDoc": "01010101010101",
      "representativeDoc": "020202020202"
    },
    {
      "dueValue": 503.67,
      "boleto": {
        "uri": "https://myurl/31260-BCA935EB-7060-466C-8415-980AE7AE596C.pdf",
        "digits": "99999999999999999999999999999999999999999999999",
        "bank": "Itaú Unibanco S.A."
      },
      "doc": "108505",
      "dueDate": "2021-03-29",
      "payerDoc": "01010101010101",
      "representativeDoc": "020202020202"
    }

  ],
  "lastEvaluated": "b59372c2-9f77-4ab3-9394-1d98a8daa5be#2021-01-05" 
}

Code:

<div id="wrapper">

    <div style="padding:1em;">
        <h4>Boletos em aberto para o cliente <?php echo$nome ?></h4>
        <p>Clique em <strong>"<i class="far fa-file-pdf" aria-hidden="true"></i> Abrir"</strong> para imprimir seus Boletos.</p>
        <h5>Acesso válido para <strong>(<?php echo$datadia ?>)</strong></h5>
    </div>
  
    <div class="container">    
        <table>
            <thead>
                <tr>
                    <th class="text-uppercase"><i class="fas fa-clock"></i> Data</th>
                    <th class="text-uppercase"><i class="fas fa-university"></i> Banco</th>
                    <th class="text-uppercase"><i class="fas fa-dollar-sign"></i> Valor</th>
                    <th class="text-uppercase"><i class="far fa-clone"></i> Dígito<span class="res digit-copied"></span></th>
                    <th class="text-uppercase"><i class="fas fa-barcode"></i> Boleto</th>
                </tr>
            </thead>
            <tbody>
                <tr>
                    <td id="demoData"></td>
                    <td id="demoBanco" class="text-uppercase blackFont"></td>
                    <td id="demoValue" class="greenFont"></td>
                    <td id="demoDigit" class="blackFont"></td>
                    <td id="demo"> </td>
                </tr>
            </tbody>
        </table>
        <!-- <div><small>Próximo > (Essa função está em desenvolvimento)</small></div> -->
        <div>
            <button id="anterior" disabled>&lsaquo; Anterior</button>
                <span id="numeracao"></span>
            <button id="proximo" disabled>Próximo &rsaquo;</button>
        </div>
    </div>


    <?php
        // test mode
        $vvv = "<div style='padding-top:10px;' class='container' id=\"objeto\"></div>";
        if ($vvv) {
           echo $vvv;
        }
    } 
    ?>

 <!-- <p style='padding-top:10px;' class='container' id="demoPagination"></p>  -->


</div><!-- /#wrapper -->
 
<script type="text/javascript"> 
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {

    if (this.readyState == 4 && this.status == 200) {

        var txt    = this.responseText;
        var objeto = JSON.parse(txt);
        
        // Checka Conteúdo
        b = objeto.items[0];
        var b;
        typeof b; 
        if ( typeof b === 'undefined' ) {  window.location.href = 'redirect.php?c=<?php echo $nome;  ?>';  }
        // Checka Conteúdo
        
        // Ordenando por data crescente
        // function custom_sort(a, b) {
        //     return new Date(a.dueDate).getTime() - new Date(b.dueDate).getTime();
        // }
        // objeto.items.sort(custom_sort);
        
        var contador=0;
        //init tloop
        objeto.items.forEach(item => { 

            var pData = document.createElement('tr');
            n = textContent = `${item.dueDate}`;
            var data = new Date(n);
            var dia  = data.getUTCDate().toString();
            var diaF = (dia.length == 1) ? '0'+dia : dia;
            var mes  = (data.getUTCMonth()+1).toString(); //+1 pois no getMonth Janeiro começa com zero.
            var mesF = (mes.length == 1) ? '0'+mes : mes;
            var anoF = data.getFullYear();
            var brData =  diaF+"/"+mesF+"/"+anoF;
            pData.append(brData);
            demoData.appendChild(pData);
            // Fim Data
 
            // Banco
            var tr3 = document.createElement('tr');
            o = textContent = `${item.boleto.bank}`;
            tr3.append(o);
            demoBanco.appendChild(tr3);
            // Fim Banco
            
            // Valor
            var tr = document.createElement('tr');
            v = textContent = `${item.dueValue}`;
            const valorFormatado = Intl.NumberFormat('pt-br', {style: 'currency', currency: 'BRL'}).format(v)
            tr.append(valorFormatado);
            demoValue.appendChild(tr);
            // Fim Valor
 
            // Dígito
            var tr4 = document.createElement('tr');
            var tr4Copy = document.createElement('span');
            v4 = textContent = `${item.boleto.digits}`;
            tr4Copy.innerHTML = '<button class="btn btn-default btn-copy btn-copy"  data-container="body" data-toggle="popover" data-placement="top" data-content="Copiado">Copiar</button>';
            tr4.append(v4);
            tr4.append(tr4Copy);
            demoDigit.appendChild(tr4);
            $('.btn-copy').on('click', function() {
                try {
                    var cell = $(this).closest('tr')[0];
                    var selection = window.getSelection();
                    var range = document.createRange();
                    range.selectNodeContents(cell);
                    selection.removeAllRanges();
                    selection.addRange(range);
                    var successful = document.execCommand('copy');
                    if (successful) {
                        // $('.res').html("Coppied");
                    
                    var alert = $('.res').html("<i class='far fa-copy'></i> Dígito Copiado");
                    alert.show();
                    setTimeout(function(){alert.html(''); }, 1500);


                    } else {
                        $('.res').html("Unable to copy!");
                    }
                } catch (err) {
                    $('.res').html(err);
                }
            });
            // Fim dígito
      
            // Link Boleto
            var pDownload = document.createElement('tr');
            var rem = document.createElement("a");
            rem.setAttribute('target', '_blank');
            rem.setAttribute( 'href', item.boleto.uri);
            rem.setAttribute('style', 'text-decoration:none;color:black;'); 
            rem.innerHTML = '<i class="far fa-file-pdf" aria-hidden="true"></i> Abrir';
            // rem.textContent = '<i class="far fa-file-pdf" aria-hidden="true"></i> Abrir'; 
            pDownload.append(rem); 
            demo.appendChild(pDownload);
            // Fim Link Boleto

            // print all
            document.getElementById("objeto").innerHTML = this.responseText;
            // print all
      
 
        })  //end my loop
 

    }
};            
 
         
           
xhttp.open("GET", "https://myurl/v1/bills?order=desc&payer=<?php echo $cnpj; ?>", true);
xhttp.setRequestHeader("x-api-key", "-");
xhttp.send();
</script> 

Trying:

I thought if the parameter lastEvaluated it is not undefined to create the button next, however do not know how I will assign on the button to pass to the next batch and then return, when there is no more the lastEvaluated.

    if (`${objeto.lastEvaluated}` !== 'undefined') {
        var button = document.createElement('button');
        button.setAttribute('type','button')
        button.appendChild(document.createTextNode('Próximo'));
        document.body.appendChild(button);            
    }

The URL that accesses the next batch looks like this:

xhttp.open("GET", "https://myurl/v1/bills?order=desc&lastEvaluated=b59372c2-9f77-4ab3-9394-1d98a8daa5be%232021-01-0&payer=<?php echo $cnpj; ?>", true);

Clarification of the author made in the comments:

Next batch records always come in the "lastEvaluated parameter"
EXAMPLE:

 `xhttp.open("GET", "https://myurl/v1/bills?order=desc&lastEvaluated=b59372c2-9f77-4ab3-9394-1d98a8daa5be%232021-01-0&payer=<?php echo $cnpj; ?>", true);`

access the next batch and so on until there are no more batches there the parameter is not set in the array.
You only need to assign this on next and previous buttons in a navigable way.
PS: There is no other parameter in the API.

  • 1

    At least from my point of view I do not have enough information about the code or documentation of that API to answer this question because I think it is necessary to either use a parameter for me still unknown or modify the code of this API to work with a new parameter in the request indicating whether to obtain the previous batch or batch following lastEvaluated.

  • 1

    the next batch records always come in the "lastEvaluated" parameter EXAMPLE: xhttp.open("GET", "https://myurl/v1/Bills?order=desc&lastEvaluated=b59372c2-9f77-4ab3-9394-1d98a5be%232021-01-0&Payer=<?php echo $cnpj; ?>", true); accesses the next batch and so on until there are no more batches so the parameter is not set in the array. You only need to assign this to the next and previous buttons in a navigable way. PS: There is no other parameter in the API.

  • 3

    How, and when you click the previous button, does the API know it is a previous pagination and not the next one? if you pass only lastEvaluated it seems to me it’s like a cursor forward only, I mean, it just goes forward, "next". In paging we usually pass the page number we want, for example 1,2, 3, etc, and who receives (can receive tbm the number of data to return) knows how to calculate which items should be returned to that page, but this example API call does not have that ,How will you know which page is next? I seem to be missing something here to solve this

  • 3

    or "lastEvaluated" would be the first item returned? if it were this logic would be possible, but I’m speculating, you need this information, otherwise there is no way to help make a pager that goes to Prox/earlier just with the information of the question

  • 2

    Just so there’s no doubt, as is formed the url of the first query to which the first ticket will return? Because this cannot be obtained by lastEvaluated.

  • @That’s how Ricardopunctual is. First Query = xhttp.open("GET", "https://myurl/v1/Bills?order=desc&payer=<?php echo $cnpj; ?>", true); If there is another batch, the lastEvaluated parameter comes in the array. EX: "lastEvaluated": "b59372c2-9f77-4ab3-9394-1d98a8daa5be#2021-01-05" If you put this parameter in the URL, it goes to another EX: xhttp open batch.("GET", "https://myurl/v1/Bills?order=desc&lastEvaluated=b59372c2-9f77-4ab3-9394-1d98a8daa5%be 232021-01-0&Payer=<?php echo $cnpj; ?>", true); If there is another batch it comes with another value in lastEvaluated EX: "lastEvaluated": "BLABLA#2021-03-05"

  • @Augustewhat is the first query xhttp.open("GET", "https://myurl/v1/Bills? order=desc&payer=<? php echo $cnpj; ? >", true); If there is another batch, the lastEvaluated parameter comes in the array. This toggle between next and previous buttons will always have to check lastEvaluated because for each batch it will have a different value if it exists. I can only see the next batch if I manually insert lastEvaluated into the URL and it looks like this: xhttp.open("GET", "https://myurl/v1/Bills? order=desc&lastEvaluated=b59372c2-9f77-4ab3-9394-1d98a8daa5be%232021-01-0&Payer=<? php echo $cnpj; ? >", true);

Show 2 more comments
No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.