Materialize Autocomplete does not load values

Asked

Viewed 636 times

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 take the return, copy and paste inside the date:, works perfectly.

Now, I would like to know how to make the date bendidto: or the source: directly load these return values. What I’m doing wrong? =(

Any idea?

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>

Print da inspeção do Navegador

Code to perform feedback is

$stmt = $pdo->prepare('SELECT id,nome from tvo_cidade where id_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);

But tmb has already used the same that I use to return the cities I load in the chained menu (that is working) that is this stretch (but that tmb does not work for the 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.

2 answers

0

This is Bruno, blz?

I think that in the return is coming a string and needs to turn into a JSON... try to use JSON.parse();

Do it like 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
});

});
  • Save William, It didn’t work tmb.. It’s a mystery this, but thanks for trying hehe... face hugging !

0

The problem is in the format of the attribute data, it is not a list, it is an object with the values defined as "texto exibido: url para ícone", as documented:

inserir a descrição da imagem aqui

You can use null as the second parameter to display text only, without an icon.

The return of post should be:

{
    "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>
<link rel="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>
<div class="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 don’t know how you’re doing to return the content, the may be detecting how text, try to add "json" as the last argument of $.post()

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
  • Hi Denis, thanks for the reply! I did this test and it worked, but I can’t make the return in this format. How could I get this return in a format that autcomplete can "read" the information, as in the city menu? Any suggestions ?

  • I managed to generate a return exactly as the object asks, but I do not know why water charges do not carry the values. If I put a console.log(return), take the output and paste in the date: works perfectly. would know how to explain why putting date: return or source:This does not happen ? Thanks

  • Add to the question how is your code, I’ll take a look

  • Save Denis, update the question, see if it helps.. thanks!

  • Can you put the whole page? I think the problem is with loading script, can also put what is returned in the console?

  • Denis, the return I put is from the post both via console and via php echo. If I just copy and paste the output (console or echo) into the date:{...} script it works normal. I guess that rules out the script loading error. But... anyway, I’ll put here a simplified version of the page + return (console)... 1 min

  • Updated Denis... see if helped... Thanks.

  • I changed the answer, take a look there

  • Hello Denis, It didn’t work tmb.... to almost give up... Thanks for the help..

Show 4 more comments

Browser other questions tagged

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