5
I make a query in the database through PHP that receives the data from an AJAX. (And then returns the query data to AJAX)
So far so good. The problem is that I would like to paginate these data returning from AJAX. (There are thousands of lines)
My biggest problem is creating these buttons, from the image below, for paging (This is an image of a page made with Datatables):
I don’t see a correct logic of how to create and display these buttons according to the number of rows returned from Mysql.
Below is a part of my AJAX, and PHP code.
function inserirFormulario(dados, select_de_filtro) {
  $("div#loading-resultado-pesquisa").html("<img src='../_imagens/load2.gif' width='300px'>");
  $("div#loading-resultado-pesquisa").show();
  $.ajax({
    //dataType: "json",
    type: "POST",
    data: dados.serialize(),
    url: "../banco/banco-vision/pagina-controle-de-tarefas/interface-resultado-pesquisa.php",
    cache: false,
  }).done(function(data) {
    var atividades = "";
    $.each($.parseJSON(data), function(chave, valor) {
      //FUNÇÃO PARA FORMATAR AS DATAS QUE VEM DO PHP
      function dataAtualFormatada(parametro) {
        if (parametro == null) {
          parametro = "";
          return parametro;
        } else {
          var data = new Date(parametro),
            dia = data.getDate().toString(),
            diaF = (dia.length == 1) ? '0' + dia : dia,
            mes = (data.getMonth() + 1).toString(), //+1 pois no getMonth Janeiro começa com zero.
            mesF = (mes.length == 1) ? '0' + mes : mes,
            anoF = data.getFullYear();
          return diaF + "/" + mesF + "/" + anoF;
        }
      }
      var vencimento = dataAtualFormatada(valor.DT_VENCIMENTO);
      var inicio = dataAtualFormatada(valor.DT_INICIO);
      var fim = dataAtualFormatada(valor.DT_FIM);
      //CRIANDO AS LINHAS COM OS TD DA TABELA QUE SÃO O RESULTADO NA CONSULTA AO BANCO 
      atividades += '<tr class="' + valor.codigo + '" name="' + valor.STATUS + '">';
      atividades += '<td nowrap>' + valor.RESPONSAVEL + '</td>';
      atividades += '<td nowrap >' + valor.COD + '</td>';
      atividades += '<td nowrap>' + (valor.EMPRESAS.substring(0, 40)) + '</td>';
      atividades += '<td nowrap >' + valor.TRIBUTACAO + '</td>';
      atividades += '<td nowrap>' + (valor.TIPO_ATIVIDADE.substring(0, 50)) + '</td>';
      atividades += '<td ">' + vencimento + '</td>';
      if (valor.STATUS == "INICIADO") {
        atividades += '<td style="padding:0;text-align:left;" class="" ><button type="button" class="btn ' + valor.STATUS + ' reabriratividade  colocarstandby justificar btn-info  css-botao-lista" value="' + valor.codigo + '">' + valor.STATUS + '</button></td>';
      } else if (valor.STATUS == "CONCLUIDO") {
        atividades += '<td  style="padding:0;text-align:left;"  class="" ><button type="button" class="btn ' + valor.STATUS + ' reabriratividade  colocarstandby justificar btn-success  css-botao-lista" value="' + valor.codigo + '">' + valor.STATUS + '</button></td>';
      } else if (valor.STATUS == "CONCLUIDO_VENCIDO") {
        atividades += '<td style="padding:0;text-align:left;"  class="" ><button type="button" class="btn ' + valor.STATUS + ' reabriratividade  colocarstandby justificar btn-dark  css-botao-lista" value="' + valor.codigo + '">' + valor.STATUS + '</button></td>';
      } else if (valor.STATUS == "VENCIDO") {
        atividades += '<td  style="padding:0;text-align:left;width:100%"  class="" ><button type="button" class="btn ' + valor.STATUS + ' reabriratividade  colocarstandby justificar btn-danger  css-botao-lista" value="' + valor.codigo + '">' + valor.STATUS + '</button></td>';
      } else if (valor.STATUS == "PENDENTE") {
        atividades += '<td  style="padding:0;text-align:left;"  class="" ><button type="button" class="btn ' + valor.STATUS + ' reabriratividade  colocarstandby justificar btn-primary  css-botao-lista" value="' + valor.codigo + '">' + valor.STATUS + '</button></td>';
      } else if (valor.STATUS == "INICIADO_VENCIDO") {
        atividades += '<td  style="padding:0;text-align:left;"  class="" ><button type="button" class="btn ' + valor.STATUS + '  reabriratividade colocarstandby justificar btn-warning  css-botao-lista" value="' + valor.codigo + '">' + valor.STATUS + '</button></td>';
      }
      //botão stand_by do status
      else if (valor.STATUS == "STAND_BY") {
        atividades += '<td  style="padding:0;text-align:left;"  class="" ><button type="button" class="btn ' + valor.STATUS + ' justificar btn-secondary css-botao-lista" value="' + valor.codigo + '">' + valor.STATUS + '</button></td>';
      }
      //botão inserir detalhes
      atividades += '<td style="padding:0;text-align:center;" ><button type="button"  class="btn btn-primary botao-detalhes css-botao-list-no-width" <a data-toggle="modal" data-target="#modal-observacoes"><span class="text-light"><i class="fas fa-comment-dots"></i></span></a></button></td>';
      //botão reabrir atividade coluna
      atividades += '<td style="padding:0;text-align:center;" class=""><button  data-placement="botton" title="Voltar o Status da atividade para o estado anterior." type="button" class="btn btn-secondary reabrir-atividade-coluna css-botao-list-no-width" name="' + valor.STATUS + '" value="' + valor.codigo + '"><span><i class="fas fa-history"></i></span></button></td>';
      //botão stand by da coluna
      atividades += '<td style="padding:0;text-align:center;" class=""><button data-placement="bottom" title="Use esta opção caso a atividade não possa ser iniciada ou concluida, devido a algum fator externo como ausência de documentação necessária dentre outros, quando a atividade for concluida fora do prazo estando em STAND BY quando o funcionario clicar na atividade novamente, o funcionário não será prejudicado, a atividade será marcada como concluída." type="button" class="btn  btn-secondary stand-by-coluna css-botao-list-no-width" id="' + valor.codigo + '"  value="' + valor.COD + '"><i class="fas fa-exclamation-circle"></i></button></td>';
      //Botão Remover linha 
      atividades += '<td style="padding:0;text-align:center;"  class=""><button  data-placement="top" title="Clique aqui para remover esta atividade, esta ação não apagará as atividades anteriores nem as futuras." type="button" class="btn btn-secondary botao-remover css-botao-list-no-width"><i class="fas fa-trash-alt"></i></button></td>';
      //Botão Justificar
      atividades += '<td style="padding:0;text-align:center;" class=" css-botao-list-no-width"><button  data-placement="top" title="A ferramenta de justificar deve ser usada, quando por algum problema alheio ao funcionário a atividade foi concluída fora do prazo de vencimento, ela será marcada como JUSTIFICADO e STATUS CONCLUIDO, não gerando prejuizo ao funcionário." type="button" class="btn btn-success botao-justificar css-botao-list-no-width"><i class="fas fa-check-circle"></i></button></td>';
      atividades += '<td style="padding:0;text-align:center;" class="th-ocultar-responsivo-tbody td-padding"><button type="button" data-toggle="tooltip" data-placement="top" title="Clique aqui para ver o arquivo" class="btn  btn-secondary css-ver-arquivo botao-ver-arquivo ' + valor.codigo + '"  value="' + valor.COD + '"><a class="text-light" href="#" data-toggle="modal" data-target="#modal-lista-arquivos-atividade" style="text-decoration:none"><span><i class="far fa-eye"></i></span></a></button></td>';
      atividades += '</tr>';
    });
    $('#registros-atividades').html(atividades);
    $("div#loading-resultado-pesquisa").hide();
  }).fail(function() {
  }).always(function() {
  });
}
<?php 
$pesquisar    = "SELECT COD, RESPONSAVEL, EMPRESAS, TRIBUTACAO, TIPO_ATIVIDADE, STATUS, DETALHES, FEEDBACK, DT_VENCIMENTO, DT_INICIO, DT_FIM, codigo, possui_arquivo FROM tbl_atividades";
			$pesquisar    .= " WHERE COD like '%$cod' AND EMPRESAS like '%$empresas' AND EMPRESA_ORIGEM like '%$user_empresa_origem_click_dashboard%' AND TRIBUTACAO like '%$tributacao' AND TIPO_ATIVIDADE like '%$atividade' AND departamento like '%$departamento_click_dashboard%' AND STATUS = 'STAND_BY' $variavel LIMIT $limit";
	
			
			$operacao_consulta = mysqli_query($conecta, $pesquisar) or die("Erro na conexão com banco de dados");	
			
					
			$retorno = array();
			while($linha = mysqli_fetch_object($operacao_consulta))
			{				
					
				$retorno[] = $linha;
						
			} 	
			
			
			echo json_encode($retorno);	
			
		break;
		
			
	}		
			
		
?>
Below is an image of how the system is now.
I’ve searched several sites and forum and I can’t get anything clear. Maybe because I’ve never done something like this (with paging). I find a lot of content, but with pure php.
Thanks for your attention. Thank you!


Okay, I get it. Pretty good. But I’ve seen something like this logic of yours on some forums. However, my difficulty is that I have a ready query code, as I showed in the example posted in the question. How would I, based on my query, send AJAX a return on this logic ? And the main question, how would I create the buttons the way I showed in the example ? I say: Previous 12345...1000 Next. That’s my real question. I’m sorry I wasn’t very clear.
– Gato de Schrödinger
And how would the logic of sending php the point where I want to select ? Example: If I press the '3' button (If it is to show 10 out of 10 records) it would only show the records from line 21 to 30.
– Gato de Schrödinger
It would be the question of actually saying which is the current page (which I assume is sent when we click on the numeric button).
– Gato de Schrödinger
How would I create these buttons listed with page numbers ?
– Gato de Schrödinger
This logic helped a lot, brother. I just had to adapt a lot to meet my need. Thank you !
– Gato de Schrödinger