简体   繁体   中英

Return data AJAX PHP

By defaut, when my system loads some data is filtered in my db and shown to the user. But my doubt is how can I call AJAX to filter some new data, and return it, changing the default values that are already set on my variables.

This is my AJAX call:

 $("#botao-filtrar").click(function(){
  $(".mask-loading").fadeToggle(1000);
  $.ajax({
    url: 'datacenter/functions/filtraDashboardGeral.php',
    type: 'POST',
    data: {rede: $("#dropdown-parceria").val()},
  })
  .done(function(resposta){
    console.log(resposta);
  })
  .always(function(){
    $(".mask-loading").fadeToggle(1000);
  })
});

And this is what I got from trying to filter some data to return it, but nothing worked:

<?php
    require_once('../../includes/conecta.php');

    $rede = $_POST['rede'];

    function buscaDados($conexao){
        $dados = array();

        $resultado = mysqli_query($conexao, "SELECT * FROM evolucao_originacao WHERE rede = {$rede}");

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

Any idea?

Thanks!

You should add echo at the end :

echo json_encode($dados);

So the $dados array will be sent back to the ajax request as JSON response.

Parse the response to json uisng $.parseJSON() :

.done(function(resposta){
     resposta = $.parseJSON(resposta);

     console.log(resposta);
})

Hope this helps.

in your ajax code u add a success.

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

    //You do not need to use  $.parseJSON(data).  You can immediately process data as array.
    console.log(data)

    //if you have a array you use the following loop

     for (var j =0;j < data.length;j++) {

    console.log(data[j]);
    // u can use data[j] and write to any fields u want.
    // e.g.
    $('.somediv').html(data[j].myarraykey);



     }

  })
  .done(function(resposta){
    console.log(resposta);
  })
  .always(function(){
    $(".mask-loading").fadeToggle(1000);
  })
});

And for the php codes (i did not check whether your code is valid or not), you need to add the echo and a die to end the call.

$rede = $_POST['rede'];

    $dados = array();

    $resultado = mysqli_query($conexao, "SELECT * FROM evolucao_originacao WHERE rede = {$rede}");

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM