Problems with paging on the search page

Asked

Viewed 239 times

2

I’m creating an input for searching my table, but I’m having problems with paging on the page where I search.

Page where I create the table and make the normal pagination:

<div id="resultado">
 <h1>Alerta Recebido</h1>
<?php if($num > 0){ ?>
    <table class="table table-responsive">  
    <thead>
        <tr> 
            <th width="20%" style="text-align:center;">De</th>
            <th width="60%" style="text-align:center;">Assunto</th>
            <th width="10%" style="text-align:center;">Prioridade</th>
            <th width="10%" style="text-align:center;">Recebido</th>                
        </tr>
        </thead>
        <tr>
        <thead>
    <?php  

        do{

         if($nomede != $produto["De"]){
    ?>  
        <th width="10%" colspan=4>Recebido: <?php echo $produto["Data"]; ?></th>
    <?php
        $nomede = $produto["De"];
        }
   ?>
        </tr>
        </thead>
        <tbody>
        <tr>  
        <td ><?php echo $produto["De"]; ?></td>
        <td class="td-info view_data apagar" id="<?php echo $produto["Id"]; ?>,<?php echo $produto["Para"]; ?>" data-toggle="modal" href="#dataModal" width="20%" <?php echo $produto["Status"] != '0'?' style="font-weight:bold; font-size: 90%" ':' style="font-weight:normal; font-size: 90%" '?>><?php echo $produto["Assunto"]; ?></td>  
        <td><?php echo $produto["Prioridade"]; ?></td> 
        <td><?php echo $produto["Hora"]; ?></td>
        </tr>
</div>          
<?php } while($produto = $result->fetch_assoc()); ?>
<tbody>
    </table>
<nav>
<ul class="pagination">
<li>
<a href="./recebidas?pagina=0" aria-label="Previous">
<span aria-hidden="true">&laquo;</span>
</a>
</li>
<?php 
for($i=0;$i<$num_paginas;$i++){
$estilo = "";
if($pc == $i)
$estilo = "class=\"active\"";
?>
<li <?php echo $estilo; ?> ><a href="./recebidas?pagina=<?php echo $i; ?>"><?php echo $i+1; ?></a></li>
<?php } ?>
<li>
<a href="./recebidas?pagina=<?php echo $num_paginas-1; ?>" aria-label="Next">
<span aria-hidden="true">&raquo;</span>
</a>
</li>
</ul>
</nav>
<?php } ?>
</div>

Then I created a form with the search input:

<form action="./busca">
    Buscar por: <input type="text" name="campo" id="campo">
</form>

Jquery:

$('#campo').keyup(function(){
    $('form').submit(function(){
        var dados = $(this).serialize();

        $.ajax({
            url: './busca',
            method: 'post',
            dataType: 'html',
            data: dados,
            success: function(data){
                $('#resultado').empty().html(data);
            }
        });

            return false;
    });
        $('form').trigger('submit');
});

On the page busca I have the code as follows:

$itens_por_pagina1 = 10;

// pegar a pagina atual
$pagina1 = intval($_GET['pagina']);
if(empty($pagina1) && $pagina1 !=0){
$pc1 = "0";
} else {
$pc1 = $pagina1;
}
$inicio1 = $pc1 - 0;
$inicio1 = $inicio1 * $itens_por_pagina1;

$campo = mysqli_real_escape_string($conn, $_POST["campo"]); 

$query1 = "SELECT Id, De, Assunto, Conteudo, Prioridade, DATE_FORMAT(Recebido,'%H:%i') AS Hora, DATE(Recebido) AS Data,
Email, Tipo, raddb.Alertas.Para, Status FROM raddb.Alertas LEFT OUTER JOIN raddb.ValAlertas
ON raddb.ValAlertas.IdSMS = raddb.Alertas.Id AND raddb.ValAlertas.Para = raddb.Alertas.Para
WHERE raddb.Alertas.Para = '$colaborador' AND De like '%$campo%' ORDER BY Recebido Desc LIMIT $inicio1, $itens_por_pagina1";

$result1 = $conn->query($query1) or die($conn->error);

$produto1 = $result1->fetch_assoc();

$num1 = $result1->num_rows;

$num_total1 = $conn->query("SELECT Id, De, Assunto, Conteudo, Prioridade, DATE_FORMAT(Recebido,'%H:%i') AS Hora, DATE(Recebido) AS Data,
Email, Tipo, raddb.Alertas.Para, Status FROM raddb.Alertas LEFT OUTER JOIN raddb.ValAlertas
ON raddb.ValAlertas.IdSMS = raddb.Alertas.Id AND raddb.ValAlertas.Para = raddb.Alertas.Para
WHERE raddb.Alertas.Para = '$colaborador' AND De like '%$campo%'  
ORDER BY Recebido Desc")->num_rows;

$num_paginas1 = ceil($num_total1/$itens_por_pagina1);

echo '
     <h1>Alerta Recebido</h1>';
    if($num1 > 0){ ?>
    <table class="table table-responsive">  
    <thead>
        <tr> 
            <th width="20%" style="text-align:center;">De</th>
            <th width="60%" style="text-align:center;">Assunto</th>
            <th width="10%" style="text-align:center;">Prioridade</th>
            <th width="10%" style="text-align:center;">Recebido</th>                
        </tr>
        </thead>
        <tbody>
        <tr>
    <?php
        do{
    ?>          
        <td ><?php echo $produto1["De"]; ?></td>
        <td class="td-info view_data apagar" id="<?php echo $produto1["Id"]; ?>,<?php echo $produto1["Para"]; ?>" data-toggle="modal" href="#dataModal" width="20%" <?php echo $produto1["Status"] != '0'?' style="font-weight:bold; font-size: 90%" ':' style="font-weight:normal; font-size: 90%" '?>><?php echo $produto1["Assunto"]; ?></td>  
        <td><?php echo $produto1["Prioridade"]; ?></td> 
        <td><?php echo $produto1["Hora"]; ?></td>
        </tr>

<?php } while($produto1 = $result1->fetch_assoc()); ?>
<tbody>
</table>
<nav>
<ul class="pagination">
<li>
<a href="./busca?pagina=0" aria-label="Previous">
<span aria-hidden="true">&laquo;</span>
</a>
</li>
<?php 
for($i=0;$i<$num_paginas1;$i++){
$estilo = "";
if($pc1 == $i)
$estilo = "class=\"active\"";
?>
<li <?php echo $estilo; ?> ><a href="./busca?pagina=<?php echo $i; ?>"><?php echo $i+1; ?></a></li>
<?php } ?>
<li>
<a href="./busca?pagina=<?php echo $num_paginas1-1; ?>" aria-label="Next">
<span aria-hidden="true">&raquo;</span>
</a>
</li>
</ul>
</nav>
<?php } ?>

It searches and shows the pagination as shown in the images:

First when I open the page without searching: inserir a descrição da imagem aqui

Second image, when searching and only fills a page, works well, as shown in the image:

inserir a descrição da imagem aqui

Third image, when I search for something that generates but than a page, at first it works well, as I show:

inserir a descrição da imagem aqui

Fourth image is where the problem arises, in the search I show in the previous image, when I change page (for example page 2) loses the filter (returns the 6 pages as in the first image) and leaves the main page and goes to the page where I do the search, as shown in the image: inserir a descrição da imagem aqui

But when changing page you should continue to show the search results inside the div, without changing page.

4 answers

1

You will need to keep the search term saved just like the page to filter later in the server query.
An example of how the URL should look like is busca?termo="xxxx"&pagina=2, and so you can collect these parameters from the URL and pass them to the server.

However, if using an external library is not a problem, I recommend using Datatables, that does everything you want and its configuration is very simple.

0

Use sessions to store in a variable, which has been searched. The way you are doing, it takes the value of the field but when switching pages this field becomes empty. You can use cookies also, but I prefer sessions.

Session example:

<?php

    session_start();
    $_SESSION["filtroBusca"] = $_POST["campo"];

?>

You can take a look at own PHP Manual - Sessions

0


I solved this way. On the page where you see the alerts I created this form:

<form class="form-inline" method="GET" action="./busca">
    <div class="form-group">
        <label for="exampleInputName2">Pesquisar</label>
        <input type="text" name="busca" class="form-control" id="exampleInputName2" placeholder="Digitar...">
    <button type="submit" class="btn btn-primary">Pesquisar</button>
    </div>
</form>

On the page of busca I put the following code: PHP:

$pagina = (isset($_GET['pagina']))? $_GET['pagina'] : 1;
if(!isset($_GET['busca'])){
    header("Location: ./recebidas");
}else{
    $valor_pesquisar = $_GET['busca'];
}

//Selecionar todos os cursos da tabela
$result_curso = "SELECT Id, De, Assunto, Conteudo, Prioridade, DATE_FORMAT(Recebido,'%H:%i') AS Hora, DATE(Recebido) AS Data,
Email, Tipo, raddb.Alertas.Para, Status FROM raddb.Alertas LEFT OUTER JOIN raddb.ValAlertas
ON raddb.ValAlertas.IdSMS = raddb.Alertas.Id AND raddb.ValAlertas.Para = raddb.Alertas.Para
WHERE raddb.Alertas.Para = '$colaborador' AND De LIKE '%$valor_pesquisar%'";
$resultado_curso = mysqli_query($conn, $result_curso);

//Contar o total de cursos
$total_cursos = mysqli_num_rows($resultado_curso);

//Seta a quantidade de cursos por pagina
$quantidade_pg = 10;

//calcular o número de pagina necessárias para apresentar os cursos
$num_pagina = ceil($total_cursos/$quantidade_pg);

//Calcular o inicio da visualizacao
$incio = ($quantidade_pg*$pagina)-$quantidade_pg;

//Selecionar os cursos a serem apresentado na página
$result_cursos = "SELECT Id, De, Assunto, Conteudo, Prioridade, DATE_FORMAT(Recebido,'%H:%i') AS Hora, DATE(Recebido) AS Data,
Email, Tipo, raddb.Alertas.Para, Status FROM raddb.Alertas LEFT OUTER JOIN raddb.ValAlertas
ON raddb.ValAlertas.IdSMS = raddb.Alertas.Id AND raddb.ValAlertas.Para = raddb.Alertas.Para
WHERE raddb.Alertas.Para = '$colaborador' AND De like '%$valor_pesquisar%' ORDER BY Recebido Desc limit $incio, $quantidade_pg";
$resultado_cursos = mysqli_query($conn, $result_cursos);
$produto = mysqli_num_rows($resultado_cursos);

Html:

<form class="form-inline" method="GET" action="./busca">
    <div class="form-group">
        <label for="exampleInputName2">Pesquisar</label>
        <input type="text" name="busca" class="form-control" id="exampleInputName2" placeholder="Digitar...">
    <button type="submit" class="btn btn-primary">Pesquisar</button>
    </div>
</form>
 <h1 style="font-size: 30px"><strong>Alerta Recebido</strong></h1>
    <table class="table table-responsive"> 

    <thead>
        <tr> 
            <th width="20%" style="text-align:center;">De</th>
            <th width="60%" style="text-align:center;">Assunto</th>
            <th width="10%" style="text-align:center;">Prioridade</th>
            <th width="10%" style="text-align:center;">Recebido</th>                
        </tr>
        </thead>
        <tr>
        <thead>
    <?php  

        do{

         if($nomede != $produto["De"]){
    ?>  
        <th width="10%" colspan=4>Recebido: <?php echo $produto["Data"]; ?></th>
    <?php
        $nomede = $produto["De"];
        }
   ?>
        </tr>
        </thead>
        <tbody>
        <tr>  
        <td ><?php echo $produto["De"]; ?></td>
        <td class="td-info view_data apagar" id="<?php echo $produto["Id"]; ?>,<?php echo $produto["Para"]; ?>" data-toggle="modal" href="#dataModal" width="20%" <?php echo $produto["Status"] != '0'?' style="font-weight:bold; font-size: 90%" ':' style="font-weight:normal; font-size: 90%" '?>><?php echo $produto["Assunto"]; ?></td>  
        <td><?php echo $produto["Prioridade"]; ?></td> 
        <td><?php echo $produto["Hora"]; ?></td>
        </tr>

<?php } while($produto = $resultado_cursos->fetch_assoc()); ?>
<tbody>
    </table>
<?php
                //Verificar a pagina anterior e posterior
    $pagina_anterior = $pagina - 1;
    $pagina_posterior = $pagina + 1;
?>
            <nav class="text-center">
                <ul class="pagination">
                    <li>
                        <?php
                        if($pagina_anterior != 0){ ?>
                            <a href="./busca?pagina=<?php echo $pagina_anterior; ?>&busca=<?php echo $valor_pesquisar; ?>" aria-label="Previous">
                                <span aria-hidden="true">&laquo;</span>
                            </a>
                        <?php }else{ ?>
                            <span aria-hidden="true">&laquo;</span>
                    <?php }  ?>
                    </li>
                    <?php 
                    //Apresentar a paginacao
                    for($i = 1; $i < $num_pagina + 1; $i++){ ?>
                        <li><a href="./busca?pagina=<?php echo $i; ?>&busca=<?php echo $valor_pesquisar; ?>"><?php echo $i; ?></a></li>
                    <?php } ?>
                    <li>
                        <?php
                        if($pagina_posterior <= $num_pagina){ ?>
                            <a href="./busca?pagina=<?php echo $pagina_posterior; ?>&busca=<?php echo $valor_pesquisar; ?>" aria-label="Previous">
                                <span aria-hidden="true">&raquo;</span>
                            </a>
                        <?php }else{ ?>
                            <span aria-hidden="true">&raquo;</span>
                    <?php }  ?>
                    </li>
                </ul>
            </nav>

This works well. There is only one problem, only search after clicking the search button that is inside the form, does not do dynamic research. But this aspect is an improvement, for now solves my problem

  • Solve with Session, which could be done dynamically and use a lot less line of code. Functions keyup and keydown are also a good call because as soon as you drop or press the keys, you can already pick up the value typed in the field and go searching.

  • @Diéfani Favareto Piovezan can put an example with Session?

  • @Diéfani Favareto Piovezan would really appreciate it if you would help me implement what you suggested...I never created a pagination and search system and the way I put it here as a response was the only one that worked

  • To activate the search while typing just activate the .change() input and then simulate the click in the form Ubmit. However, I recommend that you only simulate the click after typing a minimum number of characters, for example 3.

  • @iamdlm can put an example with change() in the input?

  • @Bruno I had put in a reply. In the comments does not format code correctly! Take a look!!!

  • @Diéfani Favareto Piovezan I saw your answer and I saw the link you put, but I could not implement. I will try again

Show 2 more comments

0

I don’t know if I understood it correctly, but trying to understand, I noticed this:

<a href="./busca?pagina=<?php echo $i; ?>">

This is your pagination, simply ?pagina={n}, but does not indicate what the search would be, I believe that this should be:

<a href="./busca?pagina=<?= $i ?>&campo=<?= $campo ?>">

That way you could know what the search is and then page about it. If you don’t want to change AJAX to GET, you could change the:

if(isset($_GET["campo") && !isset($_POST["campo"])) {
    $_POST["campo"] = $_GET["campo"]
}

$campo = mysqli_real_escape_string($conn, $_POST["campo"]); 

This can also be solved in Javascript, as it has nothing to do with what you want ("but when changing page you should continue to show the search results inside the div, without changing page.").

Add, in addition to existing code for search, this:

$('.pagination').on("click", function(e) {
    e.preventDefault();

  if (e.target instanceof HTMLAnchorElement) {
 $.ajax({
    url: e.tagert.href,
    method: 'post',
    dataType: 'html',
    data: $('form').serialize(),
    success: function(data){
      $('#resultado').empty().html(data);
    }
  });
  }



});

This will simply do the same for PHP. This will require the page on <a>, but will send the entry that is in the input, as well as turn to the search.

Browser other questions tagged

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