Filter with AJAX + PHP

2

Within my system, the user logs in, some information fetched from my database is shown, the function that searches the data and how it is listed follows:

  

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 since all data belongs 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 I click a button, it goes to the bank via an AJAX request and searches all the data in the same table that I use to enter information for the user and filters using the values selected in the dropdown.

Here's 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 have ajax return the data to me and fill in the new values in the variables I'm already using for listing without needing to reload my page!

I know it's a bit complex and I've been busting my head with it for weeks and nothing works. I am a beginner in this area of asynchronous requests.

Any solution or suggestion for improvement?

    
asked by anonymous 08.12.2016 / 17:31

2 answers

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><buttonid="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>

Test.php page 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;
    
09.12.2016 / 19:44
1

When I answer a question I usually copy code, paste it here on my server and run it to debug, but this is the kind of question I can not do because I need tables created and so on. So what you can do is try to guide you even blindly.

It looks like you're already sending the data right to the server side. Now it's time to get the answer and work on it to get you to do what you want.

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

In filterDashboardGeral.php add at the end of everything after the close of your while:

echo json_encode($dados);

And then in ajax in your function success vc treats the variable data received as an array of javascript and uses jquery to include 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, my friend. If what I have written helps you in any way, give a moral and click on the little set up to give me reputation points. Valew, falows. :)

    
08.12.2016 / 19:53