Ajax request does not work

0

I have 3 files:

newDose.php:

<label for="busca">Buscar cidadão:</label>
      <input type="text" class="form-control" id="busca" placeholder="Digite parte do nome ou o CNS" onkeypress="busca(this.value);">
      <br/>
      <table class="table table-bordered">
        <thead>
          <tr>
            <th scope="col">CNS</th>
            <th scope="col">Nome Completo</th>
            <th scope="col">Data de Nasc</th>
          </tr>
        </thead>
        <tbody id="tabelaPaciente">
          <?php
            include 'conexao.php';
            $result = mysqli_query($con, "select * from paciente limit 20");

            while ($item = mysqli_fetch_assoc($result)){
              $dataNasc = date_create($item["dataNasc"]);
              echo '<tr>
                      <td>'.$item["cns"].'</td>
                      <td>'.$item["nomePaciente"].'</td>
                      <td>'.date_format($dataNasc, "d/m/Y").'</td>
                    </tr>';
            }
          ?>
        </tbody>
      </table>

<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script src="novaDose.js"></script>

searchPHP:

include 'conexao.php';

$result = mysqli_query($con, "select * from paciente");

echo json_encode($result);

mysqli_close($con);

newDose.js:

function busca(){
$('#tabelaPaciente').empty(); //ATÉ AQUI FUNCIONA
$.ajax({
    type:'post',
    dataType:'json',
    url:'buscar.php',
    success: function(dados){
    alert(dados); //ESSE ALERTA NÃO FUNCIONA
        for(var i=0;dados.length>i;i++){
            //Adicionando registros retornados na tabela
            $('#tabela').append('<tr><td>'+dados[i].cns+'</td><td>'+dados[i].nomePaAciente+'</td><td>'+dados[i].dataNasc+'</td></tr>');
        }
    }
});
};

Apparently everything works okay, but I can not get success in the request. I use firefox and the console and network debug modules are not returning any errors.

    
asked by anonymous 22.02.2018 / 13:19

1 answer

2

I believe that a header is missing in your search.php and the fetch result needs

<?php 
header('Content-Type: application/json');

include 'conexao.php';

$result = mysqli_query($con, "select * from paciente");

echo json_encode(mysqli_fetch_all($result, MYSQLI_ASSOC));

mysqli_close($con);

?>

In your AJAX code

 dataType:'json',

This means the request is expecting a JSON as a response, but without that header in your php code, the server will respond to HTML.

Jquery slim does not contain AJAX. Use the full in:

link

    
22.02.2018 / 13:34