How to separate string in jquery from autocomplete?

Asked

Viewed 47 times

1

I’m having problems to make a search system, at the moment I do the search/comparison with 2 columns and shows the name of the 2 columns.

  $pesquisa = filter_input(INPUT_GET, 'term', FILTER_SANITIZE_STRING);

  $result_pesquisa = "SELECT Ativo, Empresa FROM tb_ativos WHERE Ativo LIKE '%{$pesquisa}%' OR Empresa LIKE '%{$pesquisa}%' ORDER BY Ativo ASC LIMIT 10";

  $resultado_final = $conn->prepare($result_pesquisa);
  $resultado_final->execute();

  while($row_pesquisa = $resultado_final->fetch(PDO::FETCH_ASSOC)){
    $data[] = $row_pesquisa['Ativo'] . " - " . $row_pesquisa['Empresa'];

  }

  echo json_encode($data);

On the main page is this excerpt

<script type="text/javascript">
      $(function(){
        $("#ativo").autocomplete({
          source: 'pesquisa-ativo.php'
        });
      });
    </script>

And returns me what I want, no matter if the user writes the corresponding name of the first or second column, will appear to msm thing for both

inserir a descrição da imagem aqui

On the main page has a code similar to the first mentioned, but showing the id tbm as a result, if I try to write any name q is in the 2 columns and give Enter it will return me to msm thing, so far so good

inserir a descrição da imagem aqui

The problem is when I click on one of the search suggestions and perform the search, as n exists in no column the junction of the two names, it n returns the search

inserir a descrição da imagem aqui

I would like to know how to get only the first word when selected one of the suggested options of the autocomplete, I believe I can deal with jquery in this code snippet, but I’m not able to do

    <script type="text/javascript">
      $(function(){
        $("#ativo").autocomplete({
          source: 'pesquisa-ativo.php'
        });
      });
    </script>

1 answer

1


Good morning Lxxx_190,

By what I intended you have a string that is mounted with 2 information to be displayed in the autocomplete, but when choosing one of the options you need to fetch the information in the bank with the 2 separate information. For this you can solve 2 ways:

  1. Separate the values with javascript "Client Side", here you break the string into an array with the separate values by always breaking the string where the given pattern is found. Here in case I determined the pattern ' - '

       const infos = string.split(' - ')
    
  2. Separate the string using php "server side", in this option you do not simply send your php the full string and separate using the "explode" method that is similar to the javascript split, also generates a string array breaking where it finds the patterns.

       $infos = explode(' - ', string)
    

after separating the Infos you can query the database looking for exactly what you want.

I hope I’ve helped!

Browser other questions tagged

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