Interpret data from an external file to use in Autocomplete

Asked

Viewed 51 times

0

I have the following file:

index php.

<script type="text/javascript">

function montaAutocomplete(source) {


 $( function() {



    var availableTags = [ source ];

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

  } );

}

</script><script>
function busca_palavra(x){

  $.ajax({
    type:"GET",
    url: "autocomplete_sugestoes_descricao.php?q=" + x,
    dataType:'text',
    success : function(data) {

        montaAutocomplete( data );

      }
    });

}
</script>

And the file that generates the result:

autocomplete_sugestoes_descricao.php

<?php

require "../conexao_ajax.php";


$q                 = preg_replace("/[^0-9A-Za-z]-/", "",$_GET['q']);

$q_formatado       =  '%'.$q.'%';


if(!empty($q)){ 
    $busca_descricao = $link->prepare("SELECT id, descricao FROM ctrl_bancario WHERE descricao LIKE ? ORDER BY descricao ASC LIMIT 10");

    $busca_descricao->bind_param("s", $q_formatado);

    $busca_descricao->bind_result($id, $descricao);

    $busca_descricao->execute();

    $busca_descricao->store_result();

    if($busca_descricao->num_rows() > 0){

        echo "[";


        while ($busca_descricao->fetch()) {

            echo "$descricao, "; 

        }// Esta chave fecha o while ($busca_descricao->fetch()) { 

            echo "]";

       } // Esta chave fecha o if($busca_descricao->num_rows() > 0){


} // Esta chave fecha if(!empty($q)){   

?>

I am being able to receive the data normally, however, if I have two records in my table:

registros

my application is returning the data this way on autocomplete of index php.:

inserir a descrição da imagem aqui

as if there was no break in line or correct interpretation of the data.

How could I proceed at the time of processing this data from the archive autocomplete_sugestoes_descricao.php in the variable var availableTags = [ source ];?

I hope to get this result:

resultado_final

  • 1

    Your problem seems to be in "availableTags", have to post it next to the question?

  • The result of my query returns just like this: [Test Deposit , test, ]

  • And "availableTags" is being declared in the first script of the index.php file

  • I am basing myself on this example to build my: https://jqueryui.com/resources/demos/autocomplete/default.html

3 answers

1

Your problem is in the form of data:

[Depósito de Teste , teste, ]

Must contain quotes or apostrophe.

var teste = ["Depósito de Teste" , "teste", ];

Use json_encode for your php to return* in the correct format

echo json_encode($result);

  $( function() {
   
      var dados= ["Depósito de Teste" , "teste" ];

     $( "#teste" ).autocomplete({
      source: dados
    });
  } );
  <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
  <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
  
  <div class="ui-widget">
  <label for="teste">teste </label>
  <input id="teste">
</div>

  • When I use 'suggestions' in a static way, it displays smoothly, however, when requirement with autocomplete_sugestoes_descricao.php it still returns in that single line

1

Compile all data coming from the database within an array and then return the array to your ajax using json_encode.

if ($busca_descricao->num_rows() > 0){
   $result = array();

    while ($busca_descricao->fetch()) {
        $result[] = $descricao;
    }
}

echo json_encode($result);

This will return an array formatted in

success: function(data) {
}
  • 1

    I used his code snippet. He just gave me a: [true,true]

  • @netoweb My mistake. I edited.

  • He returned me ["Dep u00f3sito de Teste r n","test"] when tested in the autocomplete_sugestoes_descricao.php file and tbm in the main application, still displaying everything in the same line. I would have to process this data in Success: Function(date) { } ? - If so, how would I proceed ?

  • This is probably related to how the data was recorded in the database, either by how it was sent or by how it was saved (formatting the field in the table). You need to investigate, but that’s another matter.

  • Bruno. Take a look at my answer: https://answall.com/a/233780/76180 and tell me if it is safe to use it this way.

0

I was able to find a solution:

var dados = [ source ];

var availableTags = JSON.parse(dados);

It worked perfectly, returning me this result:

It would be safe to use it this way?

inserir a descrição da imagem aqui

  • This is the solution to an extra problem, does not answer the initial question which is how to return formatted data.

  • There is no problem using JSON.parse in this comparison, as far as I know.

  • It works, but I think you should standardize your API, making it return only JSON, using echo json_encode($result); in your php returns. otherwise you need to parse* in your JS.

Browser other questions tagged

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