Filter c/ AJAX + PHP

Asked

Viewed 1,528 times

2

Within my system, the user logs in, some information searched in my database is shown, follows function that searches the data and how they are listed:

Function

# função que busca os dados de originação no banco
function listaDadosOriginacao($conexao){
    $dados = array(); //pode ser [] também, mas por compatibilidade, array()

    $rede    = $_SESSION['redeSelecionada'];
    $codLoja = $_SESSION['lojaSelecionada'];
    $mes     = $_SESSION['mesSelecionado'];

    $resultado = mysqli_query($conexao, "SELECT * FROM evolucao_originacao WHERE codLoja = {$codLoja} AND rede = '{$rede}' AND mesReferencia = '{$mes}'");
    while($valores = mysqli_fetch_assoc($resultado)){
        array_push($dados, $valores);
    }
    return $dados;
};

Listing (a single example because all data belong to the same array)

<div class="col-lg-2 col-md-6 col-sm-6 col-xs-12">
    <a class="dashboard-stat dashboard-stat-v2 green" href="#">
        <div class="visual">
            <i class="fa fa-shopping-cart"></i>
        </div>
        <div class="details">
            <div class="number"><span data-counter="counterup" data-value="<?=number_format($dadosOriginacao['propostasAprovadas'],0,',','.')?>">0</span></div>
            <div class="desc"># Aprovadas</div>
        </div>
    </a>
</div>

I have two dropdowns that filter data and when clicking a button, it goes to the database through an AJAX request and searches all the data in the same table that I use to enter information to the user and filters using the values selected in the dropdown.

Follow what I already have from the AJAX request:

$("#botao-filtrar").click(function(){
$(".mask-loading").fadeToggle(1000);
    $.ajax({
        url: 'datacenter/functions/filtraDashboardGeral.php',
        async: true,
        type: 'POST',
        dataType: 'JSON',
        data: {rede: $("#dropdown-parceria").val(), codLoja: $("#dropdown-loja").val(), mes: $("#dropdown-mes").val()},
        success: function(data){

        }
    });
});

And this is the document quoted filtraDashboardGeral.php

<?php
    session_start();
    require_once('../../includes/gestaoOriginacao.php');

    $rede = $_POST['rede'];
    $codLoja = $_POST['codLoja'];
    $mes = $_POST['mes'];

    $dados = array();

    $resultado = mysqli_query($conexao, "SELECT * FROM evolucao_originacao WHERE redeTratada = '{$rede}' and codLoja = {$codLoja} and mesReferencia = '{$mes}'");

    while($valores = mysqli_fetch_assoc($resultado)){
        array_push($dados, $valores);
    }

What I’m trying to do is, that ajax returns me the data and fill in the new values in the variables I’m already using for listing without I need to reload my page!

I know it’s a bit complex and I’ve been racking my brain about it for weeks and nothing works. I’m a beginner in this area of asynchronous requests.

Any solution or improvement suggestion?

2 answers

1

When I answer a question I usually copy code, paste here on my server and run to debug, but this is the kind of question I can’t do it because it needs created tables and so on. So what I can do is try to steer you kind of blind.

It seems that you are already sending the data in the right way to the server side. Now you have to pick up the answer and work it out to get you to do what you want.

If your intention is to take the server data and work the response with javascript, I suggest the following:

In filtraDashboardGeral.php add at the end of all, after the closure of your while:

echo json_encode($dados);

And then in ajax in its Success function vc treats the received date variable as a javascript array and uses jquery to include the variables in the html part you want.

    success: function(data)
    {
        // Aqui vc usa funções de javascript ou jquery para incluir
        // elementos do array data em partes do seu código html
        // sendo que data vai ser um array de linhas da sua 
        // tabela evolucao_originacao 

    }

Good luck there, buddy. If what I wrote helps you at all, give a moral and click the arrow up to give me reputation points. Valew, falows. :)

  • 1

    thank you very much, I was able to receive the data, in Success I put a console.log and came an array with my data filtered the way I need, but I have no idea how to do the inclusion part of the data in my html with jquery. Could you help me? (I already gave a moral by clicking on the arrow)

  • Thanks for the moral! : ) I’m leaving now, but I’ll leave you some guidance on what you’ll need: A) Locate the elements in the page’s DOM using $("#minhaid") , $(". minhaclasse") or similar mechanisms and then B) use a change of the element value or internal text of the element or add elements dynamically. Have a look at: http://www.w3schools.com/jquery/jquery_dom_add.asp and https://learn.jquery.com/using-jquery-core/manipulating-elements/

  • But I place the call of the DOM element along with append, after, etc inside the Success?

  • It can be right there in sucess or call another function to do this. One thing I like to do that helps me is to send html directly already format because I think assemble everything with more laborious javascript. I’ll paste an example into another reply using html upload instead of json.

1


Example of an ajax code:

<html>
<head>
    <script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
    <script>
    $(document).ready(function()
    {
        $('#btn1').click(function()
        {


            $.ajax({
              type: 'POST',
              url: 'test.php',
              data: {

                  variavel1: 'algumvalor',
                  variavel2: 'outrovalor',
              },
              success: function(data) 
              {
                // $('body').append(data);
                // alert(data);

                $('#minhalista').append(data);


              }
            });
        });

    });

    </script>
</head>
<body>
    <button id="btn1">
        Carregar mais elementos na lista via ajax
    </button>

    <b>Lista de Chamados<b>
    <ul id="minhalista">
        <li><a href="minhaurl.php?id=123">Elemento que já estava previamente carregado [Prioridade: Baixa]</a></li>
    </ul>


</body>
<html>

Page test.php that does the processing:

<?php

/*
 Faz algum processamento com as variáveis variavel1 e variavel2 que foram enviadas e recebe a lista abaixo
*/

// MOCKUP : Exemplo fake para ver algo funcionando
$mockuparr = array( 
                0 => array(
                            "id"             => 45,
                            "assunto"        => "Bug na listagem XPTO",
                            "prioridade"     => "Urgente"
                    ),
                1 => array(
                            "id"             => 46,
                            "assunto"        => "Mudar cor do menu para azul",
                            "prioridade"     => "Baixa"
                    ),    
                2 => array(
                            "id"             => 47,
                            "assunto"        => "Recarregar massa de testes",
                            "prioridade"     => "Média"
                    ),    
                3 => array(
                            "id"             => 48,
                            "assunto"        => "Excluir registros repetidos da tabela produtos",
                            "prioridade"     => "Alta"
                    ),        
                4 => array(
                            "id"             => 49,
                            "assunto"        => "Atualizar módulo CR45 em produção",
                            "prioridade"     => "Alta"
                    ),                            
            );


$output='';

foreach($mockuparr as $item)
{
    $output.='<li><a href="minhaurl.php?id='.$item["id"].'">'.$item["assunto"].' [Prioridade '.$item["prioridade"].']</li>';
}

echo $output;
  • It worked!! Thank you so much for your attention and patience haha! Hug

Browser other questions tagged

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