Error in autocomplete search field - PHP / AJAX

Asked

Viewed 59 times

0

Good afternoon guys, today I managed to make a progress in my code and I got to the point where I must be missing something stupid but I can’t find it. I am making an input field with search and autocomplete, where the user will look for the name of the Vendor and when selecting the name, beside should also popular the CNPJ of the same. At the moment, you are making an error in trying to search for the name, and I believe it is in the API that searches the data. How do I fix this problem in the API and get popular next to the Name, the CNPJ of the chosen vendor ?

Index code:

<!doctype html>
<html lang="pt-br">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Testando API</title>
</head>

<body>

<!-- IMPUT NORMAL SETANDO O ID DA LISTA COM AS OPÇÕES DO AUTOCOMPLETE NO ATRIBUTO 'list'-->
<input type="text" id="nome" name="nome" list="listaFornecedores">

<!-- LISTA QUE FOI SETADA NO ARIBUTO 'list' DO INPUT-->
<datalist id="listaFornecedores">


<script src="js/jquery-3.2.1.min.js"></script>
<script src="js/script.js"></script>
<script>
    init();
</script>

</body>
</html>

API code:

<?php
$servidor = 'localhost';
$usuario = 'root';
$senha = '';
$dbname = 'testevip';

$connect = mysqli_connect($servidor, $usuario, $senha, $dbname);

$letras = $_GET['letras'];

$query = "SELECT * FROM fornecedores WHERE nome LIKE '{$letras}%' ORDER BY nome ASC LIMIT 30";
$result = mysqli_fetch_assoc(mysqli_query($connect, $query));

if($result == NULL)
    return 'Nenhum resultado encontrado';

foreach ($result as $key => $fornecedor) {
    $json[] = $fornecedor;
}
return json_encode($json);
?>

AJAX / JS Code:

function init(){
    $("#nome").keyup(function(){
        if($(this).val() != ""){
            $.ajax({
                type: "GET",
                url: "API.php",
                data: {
                    "letras": $(this).val()
                },
                dataType:'json',
                //CASO DÊ TUDO CERTO
                success:function(data){
                    console.log(data);
                    //LIMPA A LISTA
                    $("#listaFornecedores").empty();
                    //PREENCHE A LISTA
                    $("#listaFornecedores").append(data);
                },
                error : function(request,error)
                {
                    alert("Request: "+JSON.stringify(request));
                }
            });
        }
    });
}

Error print:

http://prntscr.com/nr3lis

Thanks in advance for any help provided !!

  • dataType: "json" is probably missing from the Ajax header.

  • It’s not missing, it’s right there in the header.

  • Already printed json there in PHP file?

  • Yeah, but he’s giving me an error in my query, and even though I changed it, I can’t hit it. That’s why I called for help, because I’m pretty sure I’m missing something silly in the API, but I can’t identify it. When giving a print_r(), it displays the following error: Notice: Undefined index: letters in C: wamp64 www Project_vale_vip API.php on line 9

  • give a echo in the query and test it directly in the Database

  • At the bank she brought the names successfully, worked normally.

  • So you are creating json incorrectly

Show 2 more comments

1 answer

0

With the use of Ajax is not used Return.

Replace the line:

return json_encode($json);

To:

echo json_encode($json);

For cases where json is returning null is due to accentuation of the element, it is necessary to use utf8_encode for display.

Browser other questions tagged

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