Materialize Autocomplete does not load values

2

I'm having trouble loading values into the Materialize autocomplete. What happens is the following:

$().ready(function() {
    $('#sel_estado').change(function() {
      $.post('auto_cid.php', {id_estado:$('#sel_estado').val()}, function(res){
    console.log(res);
    $('#auto_cida').autocomplete({
        source:res,
        limit:5,
        minLenght:1
    });

    });
  });

Return of the post is this:

{"Acrelândia": null,"Assis Brasil": null,"Brasiléia": null,"Bujari": null,"Capixaba": null,"Cruzeiro do Sul": null,"Epitaciolândia": null,"Feijó": null,"Jordão": null,"Mâncio Lima": null,"Manoel Urbano": null,"Marechal Thaumaturgo": null,"Plácido de Castro": null,"Porto Acre": null,"Porto Walter": null,"Rio Branco": null,"Rodrigues Alves": null,"Santa Rosa do Purus": null,"Sena Madureira": null,"Senador Guiomard": null,"Tarauacá": null,"Xapuri": null}

If I get the return, copy and paste inside the date: , it works perfectly.

Now, I'd like to know how to make the date: or the blessed source: directly load these return values. What am I doing wrong? = (

Any ideas?

Page code with scripts

<body>
  <div class="container">
<div class="input-field col s12 m12">
    <select id="sel_estado" name="sel_estado">
        <option disabled selected>Selecione UF </option>
        <?php
          $stmt = $pdo->query('SELECT id,nome FROM tvo_estado ORDER BY nome');
          $stmt->execute();
          $result = $stmt->fetchAll();
          foreach($result as $estado){
              echo '<option value="'. $estado['id'] .'">'. $estado['nome'] .'</option>';
          }
        ?>
    </select>
    <label>Estado</label>
</div>

<div class="input-field col s12 m12">
  <select id="sel_cidade" name="sel_cidade">
    <option disabled selected>Selecione Cidade </option>
  </select>
  <label>Cidade</label>

  <input type="text" name="auto_cida" id="auto_cida" class="autocomplete">
</div>
<script type="text/javascript">

<!-- Habilita Menu Planos -->
$(document).ready(function(){
$('#sel_estado').formSelect();
$('#sel_cidade').formSelect();
});

$().ready(function() {
$('#sel_estado').change(function() {

  $.post('sel_cidade.php', {id_estado:$('#sel_estado').val()}, function(data){
    $.each(data, function (index, value){
        $("#sel_cidade").append("<option value=" + value.id + '">' + value.nome + '</option>');
    });
    $('#sel_cidade').formSelect();
    }, 'json');
  });

  $.post('auto_cid.php', {id_estado:$('#sel_estado').val()}, function(res){
    console.log(res);
    $('#auto_cida').autocomplete({
        source:res, //source:res ou data:res que nao muda nada copy+paste = ok
        limit:5,
        minLenght:1
    });

    });
  });

</script>
</body>
</html>

Codetoperformfeedbackis

$stmt=$pdo->prepare('SELECTid,nomefromtvo_cidadewhereid_estado="'. $id .'" ORDER BY nome ASC');
      $stmt->execute();
      $result = $stmt->fetchAll();
      $x=0;
      $aux="{";
      foreach ($result as $lines) {
           $aux .= "\"". $lines['nome'] ."\": null";
           if($x<sizeof($result)-1){
             $aux .=",";
             $x++;
           }else{
             $aux .='}';
           }
      }
      echo json_encode($aux);

I have already used the same as I use to return the cities that I load in the menu that is running (which is working), which is this section (but that does not work for autocomplete):

if($id){
      $stmt = $pdo->prepare('SELECT id,nome from tvo_cidade where id_estado="'. $id .'" ORDER BY nome ASC');
      $stmt->execute();
      $result = $stmt->fetchAll();
      echo json_encode($result);
      return;
    }

In the hope of a solution ... = '( Thank you.

    
asked by anonymous 28.07.2018 / 14:20

2 answers

0

The problem is in the format of the data attribute, it is not a list, it is an object with values set to "texto exibido: url para ícone" , according to the documentation:

Youcanusenullasthesecondparametertodisplaytextonly,withoutanicon.

Thereturnofpostshouldbe:

{"Acrelândia" :null,
    "Assis Brasil":null,
    "Brasiléia":null,
    "Bujari":null,
    "Capixaba":null,
    "Cruzeiro do Sul":null,
    "Epitaciolândia":null,
    "Feijó":null,
    "Jordão":null,
    "Mâncio Lima":null,
    "Manoel Urbano":null,
    "Marechal Thaumaturgo":null,
    "Plácido de Castro":null,
    "Porto Acre":null,
    "Porto Walter":null,
    "Rio Branco":null,
    "Rodrigues Alves":null,
    "Santa Rosa do Purus":null,
    "Sena Madureira":null, 
    "Senador Guiomard":null, 
    "Tarauacá": null,
    "Xapuri": null
  }

Below is a functional example of autocomplete:

$(document).ready(function(){
    $('input.autocomplete').autocomplete({
      data: {
        "Acrelândia" :null,
        "Assis Brasil":null,
        "Brasiléia":null,
        "Bujari":null,
        "Capixaba":null,
        "Cruzeiro do Sul":null,
        "Epitaciolândia":null,
        "Feijó":null,
        "Jordão":null,
        "Mâncio Lima":null,
        "Manoel Urbano":null,
        "Marechal Thaumaturgo":null,
        "Plácido de Castro":null,
        "Porto Acre":null,
        "Porto Walter":null,
        "Rio Branco":null,
        "Rodrigues Alves":null,
        "Santa Rosa do Purus":null,
        "Sena Madureira":null, 
        "Senador Guiomard":null, 
        "Tarauacá": null,
        "Xapuri": null
      },
    });
  });
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><linkrel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0-rc.2/css/materialize.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0-rc.2/js/materialize.min.js"></script><divclass="row">
    <div class="col s12">
      <div class="row">
        <div class="input-field col s12">
          <i class="material-icons prefix">textsms</i>
          <input type="text" id="autocomplete-input" class="autocomplete">
          <label for="autocomplete-input">Autocomplete</label>
        </div>
      </div>
    </div>
  </div>

Edit

I do not know how you're doing to return content, may be detecting like text , try adding "json" as the last argument of $.post()

It would look like this:

$.post('auto_cid.php', {id_estado:$('#sel_estado').val()}, function(res) {
    $('#auto_cida').autocomplete({
        source:res,
        limit:5,
        minLenght:1
    });
}, "json");//Aqui é o tipo de conteúdo retornado, por padrão ele tenta adivinhar, mas pode acabar reconhecendo incorretamente
    
28.07.2018 / 14:44
0

Speak Bruno, blz?

I think in return a string is arriving and needs to transform into a JSON ... try to use JSON.parse ();

Do this:

$.post('auto_cid.php', {id_estado:$('#sel_estado').val()}, function(res){

res = JSON.parse(res);
console.log(res);

$('#auto_cida').autocomplete({
    source:res, //source:res ou data:res que nao muda nada copy+paste = ok
    limit:5,
    minLenght:1
});

});
    
28.07.2018 / 23:28