Autocomplete with jquery and mysql does not list options when typing

1

I have the following form:

<?php
//CHAMA A CONEXÃO COM O BANCO DE DADOS
require('../db/conexao.php');

?>
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
    <title><?php echo $VarEmp ;?></title>
    <!-- Include all compiled plugins (below), or include individual files as needed -->
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
    <!-- Bootstrap -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

    <!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
    <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
    <!--[if lt IE 9]>
      <script src="https://oss.maxcdn.com/html5shiv/3.7.3/html5shiv.min.js"></script><scriptsrc="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
    <![endif]-->
  <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
  <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script><scripttype="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js"></script><scripttype="text/javascript">
  $(document).ready(function(){
    $("input[name='end']").blur(function(){
      var $cep    = $("input[name='cep']");
      var $cidade = $("input[name='cidade']");
      var $bairro = $("input[name='bairro']");
      var $estado = $("input[name='estado']");


      $cep.val('Carregando...');
      $cidade.val('Carregando...');
      $bairro.val('Carregando...');
      $estado.val('Carregando...');

        $.getJSON(
          '../functions/functionCEP.php',
          { end: $( this ).val() },
          function( json )
          {

            $cep.val( json.Jcep );
            $cidade.val( json.Jcidade);
            $bairro.val( json.Jbairro);
            $estado.val( json.Jestado);
          }
        );
    });
  });
  </script>
  </head>
  <body>
<!--INICIO NAVBAR-->
<nav class="navbar navbar-default">
  <div class="container-fluid">
    <!-- Brand and toggle get grouped for better mobile display -->
    <div class="navbar-header">
      <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
        <span class="sr-only">Toggle navigation</span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
      </button>
      <a class="navbar-brand" href="#">CLIENTES</a>
    </div>

    <!-- Collect the nav links, forms, and other content for toggling -->
    <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
      <ul class="nav navbar-nav">
        <li class="active"><a href="index.php">
         <span class="glyphicon glyphicon-user" aria-hidden="true"></span>
         CADASTRO
         <span class="sr-only">(current)</span></a></li>
      </ul>
      <ul class="nav navbar-nav navbar-right">
        <li><a href="../">
        <span class="glyphicon glyphicon-arrow-left" aria-hidden="true"></span>
        VOLTAR
        </a></li>
      </ul>
    </div><!-- /.navbar-collapse -->
  </div><!-- /.container-fluid -->
</nav>
<!--FINAL NAVBAR-->

<!--INICIO CONTAINER-->
<div class="container">
  <!--ROW PAINEL-->
    <!--INICIO PAINEL-->
    <div class="panel panel-default">
     <div class="panel-body">
       <!--INICIO breadcrumb-->
       <ol class="breadcrumb">
         <li><a href="../">INICIO</a></li>
         <li class="active">CADASTRO</li>
       </ol>
       <!--FINAL breadcrumb-->

      <!--INICIO FORMULARIO DE CADASTRO-->
      <form class="form-horizontal">
        <fieldset>
          <legend>DADOS CADASTRAIS</legend>

            <div class="row">
              <div class="col-md-3">
               <label for="telefone">TELEFONE</label>
               <input type="text" class="form-control" id="telefone" name="telefone" placeholder="SOMENTE NUMEROS">
             </div>
           </div>
            <div class="row">
              <div class="col-md-6">
              <label for="nome">NOME</label>
                <input type="text" class="form-control" id="nome" name="nome" placeholder="NOME DO CLIENTE">
              </div>
              <div class="col-md-3">
              <label for="rg">RG</label>
                <input type="text" class="form-control" id="rg" name="rg" placeholder="SOMENTE NUMEROS">
              </div>
              <div class="col-md-3">
              <label for="cpf">CPF</label>
                <input type="text" class="form-control" id="cpf" name="cpf" placeholder="SOMENTE NUMEROS">
              </div>
            </div>       
            <div class="row">
              <div class="col-md-2">
                 <label for="cep">CEP</label>
                   <input type="text" class="form-control" id="cep" name="cep" placeholder="SOMENTE NUMEROS">
                 </div>
              <div class="col-md-6">
                 <label for="end" >ENDERECO</label>
                   <input type="text" class="form-control" id="end" name="end" placeholder="DIGITE ENDERECO">
               </div>
              <div class="col-md-2">
                 <label for="num">NUMERO</label>
                   <input type="text" class="form-control" id="num" name="num" placeholder="NUMERO">
              </div>
              <div class="col-md-2">
                 <label for="comp">COMPLEMENTO</label>
                   <input type="text" class="form-control" id="comp" name="comp" placeholder="COMPLEMENTO">
              </div>
            </div>
            <div class="row">
              <div class="col-md-6">
              <label for="bairro">BAIRRO</label>
                <input type="text" class="form-control" id="bairro" name="bairro" placeholder="BAIRRO DO CLIENTE">
              </div>
              <div class="col-md-4">
              <label for="cidade">CIDADE</label>
                <input type="text" class="form-control" id="cidade" name="cidade" placeholder="CIDADE DO CLIENTE">
              </div>   
              <div class="col-md-2">
              <label for="estado">ESTADO</label>
                <input type="text" class="form-control" id="estado" name="estado" placeholder="SIGLA">
              </div>            
            </div>
            <div class="row">
              <div class="col-md-12">
              <label for="email">E-MAIL</label>
                <input type="text" class="form-control" id="email" name="email" placeholder="EMAIL DO CLIENTE">
              </div>
            </div>
            <div class="row">
              <div class="col-md-12">
                 <br>
                 <button type="submit" class="btn btn-primary">CADASTRAR</button>
               </div>
              </div>
        </fieldset>
        <!--FINAL FORMULARIO DE CADASTRO-->
      </form>

     <!--FINAL PAINEL-->
     </div>
    </div>
    <!--FINAL COL-MD-12-->
   </div>
   <!--FINAL ROW-->
  </div>
  <!--FINAL CONTAINER-->
 </div>
<!--FINAL CONTAINER-->  

  </body>
</html>

And I have the following function:

<?php
  /**
   * função que devolve em formato JSON os dados do cliente
   */
  function retorna( $end, $db )
  {
    $sql = "SELECT 
 r.endereco_cep        AS CEP,
 r.endereco_logradouro AS ENDERECO, 
 b.bairro_descricao    AS BAIRRO,
 c.cidade_codigo       AS CODCID,
 c.cidade_descricao    AS CIDADE,
 e.uf_sigla            AS SIGLA,
 e.uf_descricao        AS ESTADO
       FROM 
            cep_endereco AS r
            LEFT JOIN cep_bairro AS b ON b.bairro_codigo = r.bairro_codigo
            LEFT JOIN cep_cidade AS c ON c.cidade_codigo = b.cidade_codigo
            LEFT JOIN cep_uf     AS e ON e.uf_codigo = c.uf_codigo   
                 WHERE 
                  c.cidade_codigo = '3169' 
                  AND r.endereco_logradouro = '{$end}' ";

    $query = $db->query( $sql );

    $arr = Array();
    if( $query->num_rows )
    {
      while( $dados = $query->fetch_object() )
      {
        $arr['Jendereco'] = $dados->ENDERECO;
        $arr['Jcep']      = $dados->CEP;
        $arr['Jbairro']   = $dados->BAIRRO;
        $arr['Jcidade']   = $dados->CIDADE;
        $arr['Jestado']   = $dados->SIGLA;


      }
    }
    else
      $arr['Jcidade'] = 'não encontrado';

    return json_encode( $arr );
  }

if( isset($_GET['end']) )
{
  $db = new mysqli('192.168.0.1', 'root', '', 'cad');
  echo retorna( filter ( $_GET['end'] ), $db );
}

function filter( $var ){
  return $var;
}

If I enter the address correctly and hit tab or click another field fills correctly:

Themoreaccuratehedoes,thesameistruein jqueryui that is typing and he offers the options as well as filling in all fields as is already done:

WhatcouldIbedoingwrongthatisnotworking?

  

Obs:followthefunctionreturn:

{"Jendereco":"RUA A","Jcep":"35052220","Jbairro":"VISTA ALEGRE","Jcidade":"GOVERNADOR VALADARES","Jestado":"MG"}

Here is the error that is returning:

    
asked by anonymous 07.04.2017 / 21:23

2 answers

2
  

SOLUTION:

<script type="text/javascript">
    $(document).ready(function() {
        $.getJSON('../functions/functionAutoComplete.php', function(data){

            var endereco = [];


                $(data).each(function(key, value) {

                    endereco.push(value.ENDERECO);


                    });
                  $('#end').autocomplete({ source: endereco, minLength: 3});

                  console.log(endereco);


        });

    });


$(document).keydown(function(){
            $("input[name='end']").blur(function(){
                var $cep    = $("input[name='cep']");
                var $cidade = $("input[name='cidade']");
                var $bairro = $("input[name='bairro']");
                var $estado = $("input[name='estado']");


                $cep.val('Carregando...');
                $cidade.val('Carregando...');
                $bairro.val('Carregando...');
                $estado.val('Carregando...');

                $.getJSON(
                    '../functions/functionCEP.php',
                    { end: $( this ).val() },
                    function( json )
                    {

                    $cep.val( json.dados.Jcep );
                    $cidade.val( json.dados.Jcidade);
                    $bairro.val( json.dados.Jbairro);
                    $estado.val( json.dados.Jestado);
                    }
                    );
            });
        });





</script>
    
11.04.2017 / 20:38
0

You have included the jQuery UI in your code, but do not use it anywhere.

In the official documentation you can see the simplest use case of all. Autocomplete is used like this:

$( "#tags" ).autocomplete({
    source: availableTags
});

You need to select your text boxes one by one with jQuery, and for each element you must call the autocomplete function as it is in the example. Only then will you have the suggestion boxes.

    
10.04.2017 / 14:32